I would like to use $a
and $b
variables in my anonimous binary functions like it is done in sort {$a <=> $b} (1, 2, 3)
but I can not figure out why code like
#!/usr/bin/env perl
use strict;
use warnings;
Foo::Bar(sub { $a + $b });
package Foo;
sub Bar {
my ($function) = @_;
for my $i (1, 2, 3) {
local ($a, $b) = ($i, $i);
print $function->() . "\n";
}
}
does not work. While
#!/usr/bin/env perl
use strict;
use warnings;
Foo::Bar(sub { $_ });
package Foo;
sub Bar {
my ($function) = @_;
for my $i (1, 2, 3) {
local $_ = $i;
print $function->() . "\n";
}
}
works fine.
What am I doing wrong?
sort
-like function that takes a block; but that function should only return values and notprint
stuff, obviously. This is fine as a demonstration though. – Pulling