@variable
和 $variable
在 Perl 中有什么区别?
我阅读过使用符号 $
和符号 @
的变量名对应的代码。
例如:
$info = "Caine:Michael:Actor:14, Leafy Drive";
@personal = split(/:/, $info);
变量中使用 $
和 @
有什么区别?
@variable
和 $variable
在 Perl 中有什么区别?
我阅读过使用符号 $
和符号 @
的变量名对应的代码。
例如:
$info = "Caine:Michael:Actor:14, Leafy Drive";
@personal = split(/:/, $info);
变量中使用 $
和 @
有什么区别?
$
,则表示它是用于标量上下文;如果是@
,则表示该变量用于列表上下文。
my @arr;
定义了一个数组变量arr
$arr[0]
$
看作是This
(这个数字是42 <=> $number = 42
),把@
看作是These
(这些值是(1 .. 42) <=> @values = (1 .. 42)
,以及这个最后的值 <=> $values[-1]
)。 - amon@arr
是 数组,不是 列表。请看以下行为:print $s = @all = qw(my list here);
和 print $s = qw(my list here);
- gaussblurinc@one[$one]
中的@
表示列表上下文吗?但并不是所有情况都是如此。 - gaussblurinc$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
,因此是数组
以 $ 开头的变量是标量,即单个值。
$name = "david";
以@开头的变量是数组:
@names = ("dracula", "frankenstein", "dave");
如果您要引用数组中的单个值,可以使用 $
print "$names[1]"; // will print frankenstein
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.
$
代表标量变量(在您的情况下是字符串变量)。
@
代表数组。
split
函数将根据指定的分隔符(:
)拆分传递给它的变量,并将字符串放入数组中。
split
函数将标量转换为列表。然后,赋值将该列表存储在数组中。 - Dave CrossVariable 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.
$
代表标量,@
代表数组。$info
是一个包含冒号的标量字符串,@personal
是分割函数返回值被赋值的数组。split
函数接受两个参数(分隔符、待分割的值)。 - Dmitry Koroliov