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

mak*_*rek 4 perl

Perl @variable$variablePerl 之间有什么区别?

我已经在变量名称之前读取了符号$和符号的代码@.

例如:

$info = "Caine:Michael:Actor:14, Leafy Drive";
@personal = split(/:/, $info);
Run Code Online (Sandbox Code Playgroud)

什么是包含变量之间的区别$,而不是@

Ben*_*pel 6

它并不是关于变量的,而是关于变量如何使用的上下文.如果你$在变量名前加上一个,那么它在标量上下文中使用,如果你有一个@意味着你在列表上下文中使用变量.

  • my @arr;将变量定义arr为数组
  • 当您想要访问一个单独的元素(即标量上下文)时,您必须使用 $arr[0]

您可以在此处找到有关Perl上下文的更多信息:http://www.perlmonks.org/?node_id = 738558


gau*_*inc 5

关于你的所有知识的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)
Run Code Online (Sandbox Code Playgroud)

因此,listarray并不相同。

有趣的功能是切片,您的大脑将在其中发挥作用:

这段代码是神奇的:

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;
Run Code Online (Sandbox Code Playgroud)

因此,毕竟:

Perl具有有关上下文的有趣功能。您$和您@的签名,可以帮助Perl知道您想要什么,而不是您真正的意思

$s这样标量
@a这样数组