Perl变量声明中的$,@,%之间有什么区别? [英] What are the differences between $, @, % in Perl variable declaration?

查看:528
本文介绍了Perl变量声明中的$,@,%之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例:

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?

推荐答案

其中之一Perl的优点是它带有内置的手册。键入以下命令:

One of the nice things about Perl is that it comes with a built in manual. Type in the following command:

perldoc perlintro

并查看 Perl变量类型部分。您还可以在有关Perl变量的 perldoc.perl.org 部分中看到此内容。

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.

快速概述:


  • $ foo scalar 变量。它可以包含单个值,该值可以是字符串,数字等。

  • @foo array 。数组可以容纳多个值。您可以使用索引访问这些值。例如, $ foo [0] 是数组的第一个元素,而 $ foo [1] 是数组的第二个元素,依此类推。(数组通常以零开头)。

  • %foo hash ,就像一个数组,因为它可以容纳多个值,但哈希是键控数组。例如,我有一个密码哈希,称为%password 。这由用户名键入,值是用户的密码。例如:

  • $foo is a scalar variable. It can hold a single value which can be a string, numeric, etc.
  • @foo is an array. Arrays can hold multiple values. You can access these values using an index. For example $foo[0] is the first element of the array and $foo[1] is the second element of the array, etc. (Arrays usually start with zero).
  • %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} =秘密;

$password{Fred} = "swordfish"; $password{Betty} = "secret";

$ user = Fred;
print用户$ user的密码为$ password {$ user} \n; #打印出箭鱼
$ user = Betty;
print用户$ user的密码为$ password {$ user} \n; #打印出秘密

$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

请注意,当您在散列中引用单个值时或 array ,则使用美元符号。

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.

我建议您拿一本骆驼书骆驼书学习Perl ,并且是对该语言的出色介绍。

I would recommend that you get the Llama Book. The Llama Book is Learning Perl and is an excellent introduction to the language.

这篇关于Perl变量声明中的$,@,%之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆