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
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.
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.