Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "last" do in Perl?

Tags:

perl

In the code below, what does last do in the while loop? I get that if the $matrix[$i][$j]{pointer} variable equals "none" it calls last but what does it do?

Also why does the $matrix variable include score and pointer using curly braces? {score}, I read this as the 3rd dimension in an array, but is this something else? Couldn't find anything on google about this. Thanks!

my @matrix;
$matrix[0][0]{score}   = 0;
$matrix[0][0]{pointer} = "none";
#populate $matrix with more stuff

while (1) {
  last if $matrix[$i][$j]{pointer} eq "none"; #<-what is this "last" doing?
  #do some more stuff here
}
like image 303
joshweir Avatar asked Nov 29 '22 14:11

joshweir


2 Answers

Available uses for last command:

  • last LABEL

  • last EXPR

  • last

According to Perl's documentation:

The last command is like the break statement in C (as used in loops); it immediately exits the loop in question. If the LABEL is omitted, the command refers to the innermost enclosing loop. The last EXPR form, available starting in Perl 5.18.0, allows a label name to be computed at run time, and is otherwise identical to last LABEL . The continue block, if any, is not executed:

 LINE: while (<STDIN>) {
        last LINE if /^$/;  # exit when done with header
        #...
    }

last cannot be used to exit a block that returns a value such as eval {} , sub {} , or do {} , and should not be used to exit a grep or map operation. Note that a block by itself is semantically identical to a loop that executes once. Thus last can be used to effect an early exit out of such a block.

like image 198
Avihoo Mamka Avatar answered Dec 06 '22 07:12

Avihoo Mamka


You have an answer, about last but I thought I'd share this image which illustrates how next, last and redo affect logic flow in Perl loops:

enter image description here

A continue block can optionally be added to a loop to define some statements which will be run on each iteration before looping back up to the top to re-evaluate the loop condition. If there is no continue block, next will go straight back up to the loop condition.

like image 31
Grant McLean Avatar answered Dec 06 '22 07:12

Grant McLean