Why is the list my Perl map returns just 1's?

后端 未结 8 1808
时光说笑
时光说笑 2021-01-02 07:32

The code I wrote is as below :

#!/usr/bin/perl 

my @input = ( \"a.txt\" , \"b.txt\" , \"c.txt\" ) ;
my @output = map { $_ =~ s/\\..*$// } @input ;

print @o         


        
8条回答
  •  有刺的猬
    2021-01-02 07:54

    The problem: both the s/../.../ operator and Perl's map are imperative, expecting you to want to modify each input item; Perl doesn't in fact have a builtin for the functional map that yields its results without modifying the input.

    When using s, an option is to append the r modifier:

    #!/usr/bin/perl 
    
    my @input = ( "a.txt" , "b.txt" , "c.txt" ) ;
    my @output = map { s/\..*$//r } @input ;
    
    print join(' ', @output), "\n";
    

    The general solution (suggested by derobert) is to use List::MoreUtils::apply:

    #!/usr/bin/perl 
    
    use List::MoreUtils qw(apply);
    
    my @input = ( "a.txt" , "b.txt" , "c.txt" ) ;
    my @output = apply { s/\..*$// } @input ;
    
    print join(' ', @output), "\n";
    

    or copy its definition into your code:

    sub apply (&@) {
        my $action = shift;
        &$action foreach my @values = @_;
        wantarray ? @values : $values[-1];
    }
    

提交回复
热议问题