No subject
Tue Jun 4 12:17:20 MDT 2013
grep EXPR, LIST
evaluates EXPR for each element for LIST, setting $_ to the element in
LIST, and returns a new array consisting of those members of LIST for
which EXPR is true.
Think of the line
@list = grep ++$temp{$_} < 2, @list;
like this:
for each element in @list
set $_ equal to that element
add one to $temp{$_}
if $temp{$_} is less than 2
// that means we haven't encountered $_ before
add that element to the return value
Note that this preserves the order of the list.
To put it another way, every time ' ++$temp{$_} < 2 ' returns true, $_
will be added to the return array. Now, ' ++$temp{$_} < 2 ' means first
increment the value of $temp{$_} by 1, then test if it is less than 2. If
$_ has not yet been seen, then '++$temp{$_}' will set $temp{$_} to 1 and
hence $_ will be returned, otherwise it will be larger than 1 and $_ will
be ignored.
Here is an example: @list = ( 'a', 'b', 'a', 'c', 'a', 'b' ) ;
$_ = 'a', $temp{'a'} is undef, ++$temp{'a'} sets $temp{'a'} to 1
1 < 2 is true, so 'a' is added to the return value
$_ = 'b', $temp{'b'} is undef, ++$temp{'b'} sets $temp{'b'} to 1
1 < 2 is true, so 'b' is added to the return value
$_ = 'a', $temp{'a'} equals 1, ++$temp{'a'} sets $temp{'a'} to 2
2 < 2 is false, so 'a' is ignored
$_ = 'c', $temp{'c'} is undef, ++$temp{'c'} sets $temp{'c'} to 1
1 < 2 is true, so 'c' is added to the return value
$_ = 'a', $temp{'a'} equals 2, ++$temp{'a'} sets $temp{'a'} to 3
3 < 2 is false, so 'a' is ignored
$_ = 'b', $temp{'b'} equals 1, ++$temp{'b'} sets $temp{'b'} to 2
2 < 2 is false, so 'b' is ignored
That's the last element in @lsit, so the return value which is now
assigned to @list is ('a', 'b', 'c') .
Hope this helps.
Rob
More information about the LUG
mailing list