SPUG: idioms of late

Joshua Juran jjuran at gmail.com
Mon Jan 18 16:04:53 PST 2010


On Jan 18, 2010, at 3:46 PM, John W. Krahn wrote:

> Joshua Juran wrote:
>> On Jan 18, 2010, at 12:04 PM, Fred Morris wrote:
>>> Lately I've found myself doing a lot of processing of lists...  
>>> usually
>>> either listrefs, or a list of keys which can be looked up in a  
>>> hashref.
>>> I've found myself using a few idioms in place of for/while loops
>>> repeatedly, and I thought I'd share.
>>>
>>> $foo->{names} = [ map { my $x = $_; $x =~ s/\.$//o; $x; }
>>>                       @{$foo->{names}}
>>>                 ];
>>>
>>> That one munges a listref, stripping trailing dots off of all of the
>>> elements. The initial "$x = $_;" seems to be necessary. That one  
>>> seems
>>> rather pythonic to me. Generally speaking they prefer that I use  
>>> perl.
>> First of all, let me note that your use of /o does nothing, since  
>> the pattern doesn't contain any variables and therefore doesn't  
>> need to be recompiled in the first place.  You have to use a copy  
>> of $_ because $_ is read-only in map.
>
> Incorrect.  You can modify $_ but that will just modify the  
> contents of the original array because, as in a foreach loop, $_ is  
> an alias to the current element of the original array.

True.  Unless the original is read-only:

$ perl -le 'print join " ", map { my $x = $_; $x =~ s/\.$//; $x; } qw 
( foo bar. baz.. )'
foo bar baz.

$ perl -le 'print join " ", map { s/\.$//o; $_; } qw( foo bar. baz.. )'
Modification of a read-only value attempted at -e line 1.

Josh




More information about the spug-list mailing list