It might be possible in XS, but would require some pretty impressive optree manipulation. $SIG{__WARN__} is the only non-insane way to do it, but as you say, introduces some overhead.
One "solution" would be to hide the issue. Assuming you intend to export your sugar functions from a module, you can place some code in your module's import method to unimport exiting warning from its caller. Be polite though and document it.
For what it's worth, even if you can get last to work flawlessly, you'll still have problems with people using @_, caller and return inside the loop body.
This is the nicest I could get things to work using Parse::Keyword (Perl 5.14+ only)...
use v5.14; use strict; use warnings qw(all); BEGIN { package More::For; use Carp; use Exporter::Shiny our @EXPORT = qw(more); use PadWalker (); use Parse::Keyword { more => \&_parse_more }; use Scope::Upper qw( localize UP ); sub _parse_more { my $tmpvar = '@More::For::____list_' . do { state $cnt = 0; ++ +$cnt }; lex_read_space; lex_peek(7) eq 'foreach' ? lex_read(7) : lex_peek(3) eq 'for' ? lex_read(3) : croak("Expected opening parenthesis"); lex_read_space; lex_peek eq '(' ? lex_read(1) : croak("Expected opening parenthesis"); lex_read_space; my $list = parse_fullexpr; lex_read_space; lex_peek eq ')' ? lex_read(1) : croak("Expected closing parenthesis"); lex_read_space; lex_peek(2) eq 'as' ? lex_read(2) : croak("Expected 'as'"); lex_read_space; my $vars = ''; while (lex_peek ne '{') { $vars .= lex_peek(1); lex_read(1); } my $count_vars = split /\,/, $vars; lex_read(1); lex_stuff( sprintf( 'while (%s = splice(%s, 0, %d)) {', $vars, $tmpvar, $count_vars, ), ); return (sub { $tmpvar, $list }, 1); } sub more { my ($tmpvar, $list) = @_; # Fix Parse::Keyword's handling of closed over variables my $peek_my; my %closed_over = %{PadWalker::closed_over($list)}; for my $var (keys %closed_over) { $peek_my //= PadWalker::peek_my(1); $closed_over{$var} = $peek_my->{$var}; } PadWalker::set_closed_over($list, \%closed_over); localize($tmpvar, [$list->()], UP); } }; package main; use More::For; my $x = 1; my $y = 9; more for ( $x .. $y ) as ( my($a), our($b), my $c ) { say join(":", $a, $main::b, $c); } say "done";
last, next, redo, return, caller, and @_ should all work fine in the loop body. Can't say I'm massively fond of the syntax I ended up with - I didn't put that much thought into it. For short lists, it's probably slower than yours because it needs to do more set-up before the loop starts. But for longer lists it should be faster, because once the initialization is done, the loop body has just been rewritten to a plain old while/splice loop.
In reply to Re: Silencing specific warnings when executing coderef?
by tobyink
in thread Silencing specific warnings when executing coderef?
by LanX
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |