in reply to while(){}continue{}; Useful?

Were there nexts in the code? They would influence how the continue block got implemented. Consider

my $n = 10; while( $n ){ print $n--; next if $n%2; } continue{ sleep 1; }

vs.

my $n = 10; while( $n ){ print $n--; next if $n%2; sleep 1; }

I've never had to use flow control like this, but I can see that it could be theoretically useful.

Replies are listed 'Best First'.
Re^2: while(){}continue{}; Useful?
by BrowserUk (Patriarch) on Mar 03, 2010 at 17:37 UTC

    Hm. Seems to me that

    my $n = 10; while( $n ){ print $n--; next if $n%2; ## do other stuff here } continue{ sleep 1; }

    Is exactly equivalent to:

    my $n = 10; while( $n ){ print $n--; unless( $n%2 ) { ## do other stuff here } sleep 1; }

    And far clearer. (Even if you prefer the if( not $n%2 ) form.)

    There has to be a good use for it, I'm just not seeing it.


    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
      I think the concept is handling complex branching with early return in the main body and exporting operations required every time. How about something more along the lines of:
      #!/usr/bin/perl use strict; use warnings; my @array = qw(1 2 cat dog 1.3 7.2); for (@array) { if (/\./) { $_*=2; next; } if (/\d/) { $_*=4; next; } } continue { print; }

      Of course TIMTOWTDI and I'm trying to come up with a contrived example.

        I'm trying to come up with a contrived example.

        Yeah! I spent a while trying to contrive something useful too. But not only did I not find anything that couldn't be done without it. I didn't find anything that I could say was even slightly more preferable done with it.

        I really had forgotten it existed until it showed up the POD of IO::Socket::Multicast.


        Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
        "Science is about questioning the status quo. Questioning authority".
        In the absence of evidence, opinion is indistinguishable from prejudice.
Re^2: while(){}continue{}; Useful?
by AnomalousMonk (Archbishop) on Mar 03, 2010 at 19:10 UTC

    Another difficulty with this structure is that lexicals defined within the  while block are not available in the  continue block:

    >perl -wMstrict -le "my $n = 3; while ($n--) { my $i = $n * $n; } continue { print qq{n $n i $i}; } " Global symbol "$i" requires explicit package name at -e line 1. Execution of -e aborted due to compilation errors.

    I think Perl 6 addresses this through the  KEEP block (?) and related mechanisms.

    I, too, cannot remember ever using this structure explicitly, but have use it implicitly occasionally via the  -p command line switch.