in reply to Is 'last' redundant in this code?

I'm wondering if 'last' is redundant if the call to the subroutine msg includes an 'exit'.

In the small snippet you've shown, and assuming that it's not an extract from a larger program, it wouldn't take too long for a reader with basic Perl skills to untangle what you mean, though they might puzzle over why you wrote "last;" instead of "exit;", and therein lies a problem: Whenever you leave something in your code that a later reader is going to puzzle over, you increase the risk of them breaking the code if they have to change it.

A cleaner way to handle this, as previously mentioned, is to lift the "exit;" out of msg(), and either replace the "last;" with "exit;" or put the exit at the bottom of the loop. Either of these removes a source of confusion.

Consider how unambiguous it is to write:

my @array = qw(hey hello yes no key dog cat); foreach (@array) { if (/key/) { msg('Yes, key found'); exit; } } sub msg { my ($msg) = @_; print "$msg\n"; }
There's no mistaking your intent.

Replies are listed 'Best First'.
Re^2: Is 'last' redundant in this code? (better naming)
by Aristotle (Chancellor) on Apr 13, 2003 at 11:45 UTC
    The other sane alternative, of course, is to get rid of the last after renaming the function to exit_with_msg.

    Makeshifts last the longest.