On Sep 5, 2012, at 7:02 AM, Shlomi Fish wrote:
>> # remove the first 2 characters from every element of the array
>> my @array2 = map { s/^..//msx } @array1;
>>
>
> This code is wrong in two respects:
>
> 1. the map clause will return the return value of the s/// subtitution and
> will modify
> the original array in place:
>
This would be a good place to mention the /r regular expression modifier,
introduced in Perl 5.14, that makes s/// (and tr///) "non-destructive" and also
return the modified string:
% cat test.pl
#!/usr/bin/perl
use strict;
use warnings;
my @array1 = ("fc11", "fc12", "fc13");
my @array2 = map { s/^..//rmsx } @array1; # note /r modifier!
print "Array 1 is " . join(",", @array1) . "\n";
print "Array 2 is " . join(",", @array2) . "\n";
% test.pl
Array 1 is fc11,fc12,fc13
Array 2 is 11,12,13
% perl -v
This is perl 5, version 14, subversion 2 (v5.14.2) built for
darwin-thread-multi-2level
…
See 'perldoc perl5140delta' and 'perldoc perlop' for more detail (the latter
with 5.14 or later)
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/