in reply to How to use Labels

Apart from the technical issue, the algorithm is just asking for trouble. Take a look at a 'naked block' and use redo. Put a # of tries limit on your loop:

my ($tries, $success) = (0, 0); { last if ++$tries > 10; print "Flocking file: attempt # $tries ... \n"; # attempts to flock file, prints a warning if that fails # warning -- the following relies on operator # precedence (&& binds tighter than or -- # use parens if that might confuse you) flock(FILE, 2) or warn "Can't flock file: $!\n" && redo; # rest of stuff $success =1; } die "Gave up after", --$tries, " attempts." unless $success;

HTH

perl -e 'print "How sweet does a rose smell? "; chomp ($n = <STDIN>); +$rose = "smells sweet to degree $n"; *other_name = *rose; print "$oth +er_name\n"'

Replies are listed 'Best First'.
(tye)Re: How to use Labels
by tye (Sage) on Jun 20, 2001 at 02:44 UTC

    I don't really like last, redo, and next much. They have many of the same problems that lead people to complain so much about goto but they also are worse than goto in that it can take quite a bit of parsing (by the human reading the code) to figure out where they are transfering control to. You have to keep parsing past enclosing braces deciding whether each is the kind of "block" that these affect or not.

    So if you are going to use them, please use them as little as possible and try not to hide them in the code. I've experimented with out-denting these types of constructs but only very rarely find that more than marginally effective.

    So I have two big gripes with the above code. First, putting a last at the very top (or bottom) of the block is just obfuscation. Change that to: while(  ++$tries <= 10  ) { Second, your redo is quite well hidden! I'd much rather have the conditional nature of the execution of the $success= 1; line more obvious.

    How about this?

    do { if( 0 < $tries++ ) { warn "Can't flock file: $!\n"; } elsif( 10 < $tries ) { die "Gave up trying to lock file.\n"; } warn "Locking file (attempt $tries)...\n"; } while( ! flock(FILE,2) ); # Success!

            - tye (but my friends call me "Tye")