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

后端 未结 8 1810
时光说笑
时光说笑 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 08:10

    You are missing the 's' for substitution.

    $_ =~ /\..*$//
    

    should be

    $_ =~ s/\..*$//
    

    Also you might be better off to use s/\.[^\.]*$// as your regular expression to make sure you just remove the extension even when the filename contains a '.' (dot) character.

    0 讨论(0)
  • 2021-01-02 08:12

    Ok, first off, you probably meant to have $_ =~ s/\..*$// — note the missing s in your example. Also, you probably mean map not grep.

    Second, that doesn't do what you want. That actually modifies @input! Inside grep (and map, and several other places), $_ is actually aliased to each value. So you're actually changing the value.

    Also note that pattern match does not return the matched value; it returns true (if there is a match) or false (if there isn't). That's all the 1's you're seeing.

    Instead, do something like this:

    my @output = map {
        (my $foo = $_) =~ s/\..*$//;
        $foo;
    } @input ;
    

    The first copies $_ to $foo, and then modifies $foo. Then, it returns the modified value (stored in $foo). You can't use return $foo, because its a block, not a subroutine.

    0 讨论(0)
提交回复
热议问题