SPUG: Grep syntax

Bill Campbell bill at celestial.com
Fri Jun 15 13:09:12 PDT 2007


On Fri, Jun 15, 2007, John W. Krahn wrote:
>Bill Campbell wrote:
>> 
>> The author of the perl (Net::CIDR from CPAN) seems to like using grep as a
>> method of processing arrays while doing no regular expression checking.  He
>> also does things like this to create an array, @bcopy, the same size as @b,
>> populated with 255.  This also takes advantage of perl's ``magic'' where
>> looping through an array allows one to modify elements of the array by
>> manipulating $_;
>> 
>> my @bcopy = @b;
>> grep { $_ = 255 } @bcopy;
>
>Or you could do that like this:
>
>$_ = 255 for my @bcopy = @b;

My biggest problem with this is that, without comments, many people
wouldn't realize that ``$_ = 255'' in this loop context is modifying the
contents of the @bcopy array.  I must admit that I've used this ``feature''
of perl many times, but I don't find it intuitively obvious.

Would bcopy still exist outside of this statement?  I would think that the
``my'' in the loop would be interpreted as local to the loop.

I tend to write code defensively, and break things into steps to be sure
that the language is doing what I want, something like this:

my @bcopy = ();
for (@b) {
	push(@bcopy, 255);
}

There's no possible ambiguity with this.

Bill
--
INTERNET:   bill at Celestial.COM  Bill Campbell; Celestial Software LLC
URL: http://www.celestial.com/  PO Box 820; 6641 E. Mercer Way
FAX:            (206) 232-9186  Mercer Island, WA 98040-0820; (206) 236-1676

``I have no reason to suppose that he, who would take away my Liberty, would
not when he had me in his Power, take away everything else.''  John Locke


More information about the spug-list mailing list