【问题标题】:Why does passing an array element print 1 instead of the string I passed?为什么传递数组元素打印 1 而不是我传递的字符串?
【发布时间】:2014-04-04 05:29:26
【问题描述】:

如果我这样做:

foreach my $comp (@compList){
  print $comp .= "\n";
  @component_dirs = DoStuff($comp); 
} 

我的输出很简单:

String1
String2
String3
...

但是,一旦我进入DoStuff() 方法,我就会这样做:

sub DoStuff{
  my $strComponentName = @_;
  print "\t$strComponentName\n";
}

这样,我的输出变成了

String1
        1
String2
        1
String3
        1
...

为什么?

【问题讨论】:

标签: arrays perl parameters


【解决方案1】:

您正在将数组 @_ 分配给标量 $strComponentName

在标量上下文中,数组的结果是数组中元素的数量。

在你的情况下它是 1,因为你用一个参数调用 DoStuff

要实际获取参数,您必须编写

my ($strComponentName) = @_;

这会将一个数组分配给一个数组,其中左侧数组中的第一个变量将包含右侧数组的第一个元素。

【讨论】:

    【解决方案2】:

    要捕获数组@_ 的元素,你的左边必须是一个列表:

    sub DoStuff{
      my ($strComponentName) = @_;
    

    否则,数组将在 scalar 上下文中进行评估,并且只会返回元素计数。

    另一种选择是在作业中指定您想要的特定元素。

      my $strComponentName = $_[0];
    

    或者shift数组中的第一个元素

      my $strComponentName = shift;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-24
      • 1970-01-01
      • 2021-04-28
      • 1970-01-01
      • 2011-12-03
      • 1970-01-01
      • 1970-01-01
      • 2021-01-29
      相关资源
      最近更新 更多