in reply to Re: coderefs and (&) prototypes
in thread coderefs and (&) prototypes
The execution of the argument passed to grep is deferred until after grep is called, and it is called once for every following argument.
sub func {} my $x; sub foo { ++$x } $x = 0; func foo(), 1,2,3; print "$x\n"; # 1 $x = 0; grep foo(), 1,2,3; print "$x\n"; # 3
grep and map don't have a prototype since this ability can't be prototyped.
You seem to think there's something special about &cb when passed to grep. It's not.
grep &cb, ... === grep { &cb } ... grep &cb(), ... === grep { &cb() } ... grep $cb->(), ... === grep { $cb->() } ... grep /.../, ... === grep { /.../ } ... grep substr($_, 2), ... === grep { substr($_, 2) } ...
(minus the extra scope).
&cb means "call non-builtin cb without changing or localising @_", whether it's the first arg of grep or otherwise.
grep cannot accept a ‘calculated’ first argument. [...] Can anyone (like ikegami :-) ) clarify for me?
Using map since it's easier to visualize,
sub mymap (&@) { my ( $code, @list ) = @_; map &$code, @list } sub get_cb { return sub { uc } } print(( mymap \&{ &get_cb }, qw( a b c ) ), "\n"); print(( map &get_cb, qw( a b c ) ), "\n"); print(( map get_cb, qw( a b c ) ), "\n"); print(( map get_cb(), qw( a b c ) ), "\n");
ABC CODE(0x1829a54)CODE(0x1829a54)CODE(0x1829a54) CODE(0x1829a54)CODE(0x1829a54)CODE(0x1829a54) CODE(0x1829a54)CODE(0x1829a54)CODE(0x1829a54)
Just can't do it. The first arg of map and grep is never evaluated before map or grep is called.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: coderefs and (&) prototypes
by JadeNB (Chaplain) on Jul 28, 2009 at 17:59 UTC | |
by ikegami (Patriarch) on Jul 28, 2009 at 18:28 UTC |