Perl变量声明中的$、@、%有什么区别?
示例:
my $some_variable;
my @some_variable;
my %some_variable;
我知道,@
似乎是数组,$
是基元,完全正确吗? %
是做什么用的?
Example:
my $some_variable;
my @some_variable;
my %some_variable;
I know, @
seems to be for array, $
for primitive, is it totally right?
What is %
for?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Perl 的优点之一是它带有内置手册。输入以下命令:
并查看 Perl 变量类型 部分。您还可以通过 perldoc.perl.org 有关 Perl 变量的部分在线查看此内容。
快速概述:
%foo 是一个哈希,这就像一个数组,因为它可以保存多个值,但哈希是键控数组。例如,我有一个名为 %password 的密码哈希。这是由用户名键入的,值是用户的密码。例如:
$password{Fred} = "剑鱼";
$password{贝蒂} = "秘密";
$user = "弗雷德";
print "用户 $user 的密码是 $password{$user}\n"; #打印出剑鱼
$用户=“贝蒂”;
print "用户$user的密码是$password{$user}\n"; #Prints out Secret
请注意,当您引用哈希或数组中的单个值时,您可以使用美元符号。对于初学者来说有点混乱。
我建议您购买骆驼书。 Llama 书是学习 Perl,是对该语言的出色介绍。
One of the nice things about Perl is that it comes with a built in manual. Type in the following command:
and take a look at the section Perl variable types. You can also see this on line with the perldoc.perl.org section on Perl variables.
A quick overview:
%foo is a hash, this is like an array because it can hold more than one value, but hashes are keyed arrays. For example, I have a password hash called %password. This is keyed by the user name and the values are the user's password. For example:
$password{Fred} = "swordfish";
$password{Betty} = "secret";
$user = "Fred";
print "The Password for user $user is $password{$user}\n"; #Prints out Swordfish
$user = "Betty";
print "The Password for user $user is $password{$user}\n"; #Prints out secret
Note that when you refer to a single value in a hash or array, you use the dollar sign. It's a little confusing for beginners.
I would recommend that you get the Llama Book. The Llama Book is Learning Perl and is an excellent introduction to the language.
$
用于标量,@
用于数组,%
用于哈希。有关详细信息,请参阅文档的变量类型部分。$
is for scalars,@
is for arrays, and%
is for hashes. See the Variable Types section of the docs for more information.$
是标量,@
是数组,%
是哈希。$
is scalar,@
is array, and%
is hash.$var 表示单值标量变量
@var 表示一个数组
%var 表示关联数组或哈希(它们都是相同的)
$var denotes a single-valued scalar variable
@var denotes an array
%var denotes an associative array or hash (they are both the same)