On 12/01/2011 17:51, shawn wilson wrote:
On Jan 12, 2011 12:10 PM, "Uri Guttman"<u...@stemsystems.com> wrote:
"R" == Ruud<rvtol+use...@isolution.nl<rvtol%2buse...@isolution.nl>>
writes:
R> On 2011-01-11 11:44, Uri Guttman wrote:
>> these are equivilent:
>>
>> my @out = grep /foo/, @in ;
>> my @out = map { /foo/ ? $_ : () } @in ;
R> Indeed equivalent. There is a difference though
R> in what comes out of map and grep:
R> perl -wle'
R> my @in = 1 .. 4;
R> print "@in";
R> ++$_ for map { $_ % 2 ? $_ : () } @in; # copies
R> print "@in";
R> ++$_ for grep { $_ % 2 } @in; # aliases
R> print "@in";
R> '
R> 1 2 3 4
R> 1 2 3 4
R> 2 2 4 4
Ok, why would that not through an error about directly modifying $_ or is it
only that $_ =~ s/something/me isn't allowed?
Direct modification of $_ isn't prohibited in any way, so substitution
is also fine although inadvisable within a map block.
$_ =~ s/something/me
isn't valid Perl, so I'm not exactly sure what you mean.
What does that 'for' do outside of map/grep?
It is a statement modifier, although I know it looks a little odd as all
the work is done after the for. The statement ++$_ is executed for each
element of the list returned by map/grep. This is from
perldoc perlsyn:
The "foreach" modifier is an iterator: it executes the statement once
for each item in the LIST (with $_ aliased to each item in turn).
print "Hello $_!\n" foreach qw(world Dolly nurse);
HTH,
Rob
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/