简体   繁体   English

在标量语境中展平Perl数组的方法

[英]Ways to Flatten A Perl Array in Scalar Context

I recently started learning perl and have a question that I'm not finding a clear answer to on the Internet. 我最近开始学习perl并且有一个问题,我在互联网上找不到明确的答案。 say I have something like this, 说我有这样的事情,

@arr = (1, 2, 3);
$scal = "@arr"
# $scal is now 123.

Is the use of quotes the only way to flatten the array so that each element is stored in the scalar value? 是否使用引号来展平数组以使每个元素都存储在标量值中? It seems improbable but I haven't found any other ways of doing this. 这似乎不太可能,但我还没有找到任何其他方法来做到这一点。 Thanks in advance. 提前致谢。

The join function is commonly used to "flatten" lists. join函数通常用于“展平”列表。 Lets you specify what you want between each element in the resulting string. 允许您在结果字符串中指定每个元素之间的内容。

$scal = join(",", @arr);
# $scal is no "1,2,3"

In your example, you're interpolating an array in a double-quoted string. 在您的示例中,您将在双引号字符串中插入数组。 What happens in those circumstances is is controlled by Perl's $" variable. From perldoc perlvar : 在这些情况下发生的事情是由Perl的$"变量控制。来自perldoc perlvar

$LIST_SEPARATOR $ LIST_SEPARATOR

$" $”

When an array or an array slice is interpolated into a double-quoted string or a similar context such as /.../ , its elements are separated by this value. 当数组或数组切片内插到双引号字符串或类似的上下文(如/.../)时,其元素由此值分隔。 Default is a space. 默认是一个空格。 For example, this: 例如,这个:

print "The array is: @array\\n";

is equivalent to this: 相当于:

print "The array is: " . join($", @array) . "\\n";

Mnemonic: works in double-quoted context. 助记符:在双引号上下文中工作。

The default value for $" is a space. You can obviously change the value of $" . $"的默认值是一个空格。显然可以更改$"的值。 $"

{
  local $" = ':',
  my @arr = (1, 2, 3);
  my $scalar = "@arr"; # $scalar contains '1:2:3'
}

As with any of Perl's special variables, it's always best to localise any changes within a code block. 与任何Perl的特殊变量一样,最好将本地化代码块中的任何更改。

You could also use join without any seperator 您也可以在没有任何分隔符的情况下使用join

my $scalar = join( '' , @array ) ;

There is more than one way to do it. 有不止一种方法可以做到这一点。

in the spirit of TIMTOWTDI: 本着TIMTOWTDI的精神:

my $scal;
$scal .= $_ foreach @arr;

Read section Context in perldata . 阅读perldata 上下文部分 Perl has two major contexts: scalar and list. Perl有两个主要的上下文:标量和列表。

For example: 例如:

@a = (1, 1, 1);   # list context
print @a;         # list context
$count = @a;      # scalar context, returns the number of elements in @a

etc. 等等

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM