Re: Readline using foreach and while
- From: Ben Morrow <ben@xxxxxxxxxxxx>
- Date: Sat, 29 Mar 2008 02:48:53 +0000
Quoth "szr" <szrRE@xxxxxxxxxxxxxxx>:
Ben Morrow wrote:
Quoth "szr" <szrRE@xxxxxxxxxxxxxxx>:
Actually the behaviors of "for (@ary)" and "for (@ary, ())" do seem
consistant if you really think about it. The resulting list is what
it iterates over (from the first element, to what ever *count* is...
in the former case *count* come fro mthe array, and since the
condition is checked at the start of each iteration, if the array is
added to, the count is incremented.
In the latter case, a new list is created from contents of @ary + an
empty list, which gives you a new list, which contains the values of
@ary, but is a new seperate list, and thus is not effected by
changes to @ary because it has it's own copy of @ary's values.
OK, now explain to me why
my @ary = qw/a b c/;
print map { /c/ and push @ary, 'd'; $_ } @ary;
*doesn't* work like that :).
Actually it does. The difference is, map doesn't recheck the count every
time around like for/foreach do. If you print the contents of @ary after
the line with the map statement, it does indeed contain 'd' at the end.
This behavior seems to correct, as one would likely expect that the list
map returns when it is finished to be the same length as the one
/passed/ into map at the start. If you pass a 3 element list, you should
get back a 3 element list, should you not?
Absolutely not. my %h = map { $_ => 1 } qw/a b c/; is quite a common
idiom.
<snip>
$_ is aliased to the current array element just like in for. Again, the
only difference I see if that map doesn't recheck the count of the
passed list for each iteration.
No, you're misunderstanding the difference between a list and an array.
Evaluating an array in list context returns a list of its elements *as
they are now*; under most circumstances, it returns a list of aliases to
those elements, but any changes to the order of the elements in @ary are
not propagated into the list. Consider
my @ary = qw/a b c/;
sub foo {
my @keep = map "$_", @_; # kill the aliasing
unshift @ary, 'h';
$_[$_] .= $keep[$_] for 0..$#_;
}
foo @ary;
print for @ary;
To me, this behavior is part of what separates map from for/foreach.
It separates for (LIST) from everything else that accepts a LIST. This is
why I called it 'weird'.
Ben
.
- Follow-Ups:
- Re: Readline using foreach and while
- From: szr
- Re: Readline using foreach and while
- References:
- Readline using foreach and while
- From: Saurabh Jain
- Re: Readline using foreach and while
- From: szr
- Re: Readline using foreach and while
- From: Ben Morrow
- Re: Readline using foreach and while
- From: szr
- Readline using foreach and while
- Prev by Date: Re: Readline using foreach and while
- Next by Date: Re: sockets giving me gray hairs. server keeps dying
- Previous by thread: Re: Readline using foreach and while
- Next by thread: Re: Readline using foreach and while
- Index(es):
Relevant Pages
|