Hi Monks,
I'd like to make a return from subroutine by the code running in a BLOCK.
I noticed how grep is working in the question:
sub working
{
my @a = (1);
grep { print "grep\n"; return 'leave' } @a;
print "Still here #1\n";
}
working;
__DATA__
grep
So, "Still here #1" is never shown.
grep is a Perl function, but I'd like to get such behaviour in a BLOCK of my own subroutine. Below is my example:
sub mygrep (&@) {
my $code = shift;
my @result;
foreach $_ (@_) {
push(@result, $_) if &$code;
}
@result;
}
sub notworking
{
my @a = (1);
mygrep { print "mygrep\n"; return 'leave' } @a;
print "Still here #2\n";
}
notworking;
__DATA__
mygrep
Still here #2
And this is nothing like original grep makes.
So, the question is: How to run a code in BLOCK passed to a subroutine and call return in a caller?
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.