Perl 入门 之 context 标量上下文与列表上下文

Perl 入门 之 context 标量上下文与列表上下文

context 上下文

perl 最独特的特性就在于 它的代码对于上下文是敏感的。

每个perl的表达式要么在 scalar 上下文中求值,要么在列表上下文求值


my $scalar = "mendeleev";  #赋值  标量上下文
my @array = ("Alpha", "Beta", "Gamma", "Pie");  #列表上下文
my ($perl, $python, $R) = ("perl", "python", "R");  #列表上下文 
my ($perl) = ("perl", "python", "R");  #还是列表上下文 
my $perl= ("perl", "python", "R");  # 标量上下文 

上下文的应用:

#初始化 array 和 hash

my @array = ("Alpha", "Beta", "Gamma", "Pie");
my %hash = ("Alpha" => "Beta", "Gamma" => "Pie");


在标量上下文中求值的列表表达式会返回 列表 中的最后一个scalar(使用非常少见):

my $scalar = ("Alpha", "Beta", "Gamma", "Pie");# $scalar的值现在是"Pie"


在标量上下文中求值的array(还记得array和列表不同吗?)表达式返回该数组的长度(较常用):

my @array = ("Alpha", "Beta", "Gamma", "Pie");
my $scalar = @array; # $scalar的值现在是4


print内置函数在列表上下文中求对所有的参数求值。

事实上,print能够接受无限个参数的列表,并且一个接一个地打印它们,这就意味着我们可以直接用它来打印array:


my @array = ("Alpha", "Beta", "Goo");
my $scalar = "-X-";
print @array;              # "AlphaBetaGoo";
print $scalar, @array, 98; # "-X-AlphaBetaGoo98";


强制标量上下文获得数组的长度:


@name=qw(perl R python shell);
print @name,"/n";      # perlRpythonshell
print scalar @name,"/n";# 3,强制指定标量上下文


  • 发表于 2018-12-24 16:47
  • 阅读 ( 2805 )
  • 分类:perl

0 条评论

请先 登录 后评论
omicsgene
omicsgene

生物信息

658 篇文章

作家榜 »

  1. omicsgene 658 文章
  2. 安生水 328 文章
  3. Daitoue 167 文章
  4. 生物女学霸 120 文章
  5. 红橙子 78 文章
  6. CORNERSTONE 72 文章
  7. xun 68 文章
  8. rzx 67 文章