簡體   English   中英

為什么pop / shift無法在perl中使用map / grep

[英]why pop/shift not work with map/grep in perl

我希望在mapgrep操作之后得到第一個或最后一個元素。 使用mapgrep shiftpop操作符似乎不起作用。 有什么建議么? 如果我將map結果保存到數組變量並且彈出那個但我想在一行中執行它,它的工作原理。

:$ cat map.pl 
use strict;
use warnings;
my @arr = (1,2,3,4);
my $ele = pop ( map{10* $_ } @arr ) ;
print "\n element is $ele";
:$ perl map.pl
Not an ARRAY reference at map.pl line 4.
map{10* $_ } @arr

生成一個列表,其元素是@arr相應元素乘以10 不會產生數組。 因此,你不能pop任何東西。 您可以訪問最后一個元素:

(map 10 * $_, @arr)[-1]

但是,地圖不會改變@arr 如果你想這樣做,

 $_ *= 10 for @arr;

map更合適。

shiftpop的第一個參數必須是數組( @NAME@BLOCK ),而不是mapgrep運算符(與數組無關)。

你可以構建一個從中shift / pop的數組。

my $first_ele = shift @{ [ map { 10 * $_ } @arr ] };           # If you want first
my $last_ele  = pop   @{ [ map { 10 * $_ } @arr ] };           # If you want last

但這非常浪費。 您可以使用列表分配或列表切片來避免創建陣列。

my ($first_ele) = map { 10 * $_ } @arr;                        # If you want first
my $first_ele = ( map { 10 * $_ } @arr )[0];                   # If you want first
my $last_ele  = ( map { 10 * $_ } @arr )[-1];                  # If you want last
my ($first_ele, $last_ele) = ( map { 10 * $_ } @arr )[0, -1];  # If you want both

但這仍然是浪費。 當您只想要最后一個產品時,不需要將所有元素相乘。 以下更有意義:

my $first_ele = 10 * $arr[0];                                  # If you want first
my $last_ele  = 10 * $arr[-1];                                 # If you want last
my ($first_ele, $last_ele) = map { 10 * $_ } @arr[0, -1];      # If you want both

在列表上下文中, mapgrep生成列表,但shift / unshiftpush / pop對數組進行操作。 列表和數組在Perl中不是一回事 你不應該擔心嘗試在一行中做所有事情,而更擔心編寫正確的代碼。

首先還是最后? 首先你可以使用

    use strict;
    use warnings;
    my @arr = (1,2,3,4);
    my ($ele) = map{10* $_ } @arr;
    print "\n element is $ele\n\n";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM