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
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];
}