What does “last” do in Perl?

两盒软妹~` 提交于 2020-12-09 06:56:41

问题


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
}

回答1:


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.




回答2:


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:

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.




回答3:


As you've already gotten an answer about last, I'll address the second part of your question. Perl has arrays and hash tables (also known as dictionaries). @matrix at the top level is an array, but then its being initialized with another array, and the element in that second array is being initialized with a hash table.

If you used Data::Dumper to print this out, or exported it as JSON you'd see something like:

@matrix= [ 
  [
    { score => 0,
      pointer => 'none'
    }
  ]
] ;


来源:https://stackoverflow.com/questions/38170411/what-does-last-do-in-perl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!