Perl中"@"和"$"的区别

6

@variable$variable 在 Perl 中有什么区别?

我阅读过使用符号 $ 和符号 @ 的变量名对应的代码。

例如:

$info = "Caine:Michael:Actor:14, Leafy Drive";
@personal = split(/:/, $info);

变量中使用 $@ 有什么区别?


1
$代表标量,@代表数组。$info是一个包含冒号的标量字符串,@personal是分割函数返回值被赋值的数组。split函数接受两个参数(分隔符、待分割的值)。 - Dmitry Koroliov
1
这是一个关于Perl中this、that和those之间区别的问题。 - daxim
1
perlintro 中有非常好且简明的描述! - rubber boots
6个回答

7
这并不仅仅涉及到变量本身,更与上下文有关。如果在变量名前面加上$,则表示它是用于标量上下文;如果是@,则表示该变量用于列表上下文。
  • my @arr; 定义了一个数组变量arr
  • 若要访问单个元素(这是一种标量上下文),需要使用$arr[0]
更多关于Perl上下文的信息请参见:http://www.perlmonks.org/?node_id=738558

好答案。你也可以把$看作是This这个数字是42 <=> $number = 42),把@看作是These这些值是(1 .. 42) <=> @values = (1 .. 42),以及这个最后的值 <=> $values[-1])。 - amon
1
@arr数组,不是 列表。请看以下行为:print $s = @all = qw(my list here);print $s = qw(my list here); - gaussblurinc
我想了解单切片的列表和标量上下文,请告诉我。 在这里,@one[$one]中的@表示列表上下文吗?但并不是所有情况都是如此。 - gaussblurinc

6
你不了解Perl的背景,所有你知道的关于它的知识都将被摧毁。
像许多人一样,你在说话时使用单个值(标量)和一组物品。所以它们之间的区别是:
我有一只猫。 $myCatName = 'Snowball'; 它跳上床,坐在那里的朋友们有@allFriends = qw(Fred John David); 你可以计算它们的数量:$count = @allFriends; 但是不能计算名字列表的总数:$nameNotCount = (Fred John David); 因此,最终:
print $myCatName = 'Snowball';           # scalar
print @allFriends = qw(Fred John David); # array! (countable)
print $count = @allFriends;              # count of elements (cause array)
print $nameNotCount = qw(Fred John David); # last element of list (uncountable)

所以,列表数组并不相同。

有趣的特性是切片,这时你的思维将与你开个小玩笑:

这段代码真是神奇:

my @allFriends = qw(Fred John David);
$anotherFriendComeToParty =qq(Chris);
$allFriends[@allFriends] = $anotherFriendComeToParty; # normal, add to the end of my friends
say  @allFriends;
@allFriends[@allFriends] = $anotherFriendComeToParty; # WHAT?! WAIT?! WHAT HAPPEN? 
say  @allFriends;

所以,总的来说:

Perl有一个有趣的特性,即上下文。你的$@是标识符,它们帮助Perl知道你想要什么,而不是你实际意思。

$s,因此是标量
@a,因此是数组


4

以 $ 开头的变量是标量,即单个值。

   $name = "david";

以@开头的变量是数组:

   @names = ("dracula", "frankenstein", "dave");

如果您要引用数组中的单个值,可以使用 $

   print "$names[1]"; // will print frankenstein

3

From perldoc perlfaq7

What are all these $@%&* punctuation signs, and how do I know when to use them?

They are type specifiers, as detailed in perldata:

$ for scalar values (number, string or reference)
@ for arrays
% for hashes (associative arrays)
& for subroutines (aka functions, procedures, methods)
* for all types of that symbol name. In version 4 you used them like
  pointers, but in modern perls you can just use references.

2

$代表标量变量(在您的情况下是字符串变量)。

@代表数组。

split函数将根据指定的分隔符(:)拆分传递给它的变量,并将字符串放入数组中。


1
严谨地说,split函数将标量转换为列表。然后,赋值将该列表存储在数组中。 - Dave Cross
$n是一个标量(这里是数组的索引),而$array[$n]将是另一个标量变量。 - Vijay

1
Variable name starts with $ symbol called scalar variable.
Variable name starts with @ symbol called array.

$var -> can hold single value.
@var -> can hold bunch of values ie., it contains list of scalar values.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接