top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

trying to figure out what `last' actually does in perl

0 votes
312 views

trying to figure out what `last' actually does, I wrote this test script:

use strict;
use warnings;
use autodie;

my $counter = 0;

while($counter < 8) {
 last if($counter > 2) {
 print "if: " . $counter . "n";
 }
 else {
 print "else: " . $counter . "n";
 }
 $counter++;
}

Unfortunately, that gives syntax errors. I would expect the following output:

else: 0
else: 1
else: 2
if: 3

What's wrong with that (letting aside that it is terribly ambiguous)?

posted Jun 17, 2013 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

0 votes

You have a post statement if and then a code block. You can only use one of two forms:

print "test" if $color eq "blue"; #no parenthesis required
 if($color eq "blue"){print "test";}

As far as last, http://perldoc.perl.org/functions/last.html
The example given:

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

What theyre saying here is that it breaks out of a loop. Its not like a return where it breaks out of a subroutine, it just continues beyond the loop. I think this fixes your program:

use strict;
use warnings;
use autodie;

my $counter = 0;

while($counter < 8) {
    if($counter > 2) {
         print "if: " . $counter . "n";
        last;
    }
    else {
         print "else: " . $counter . "n";
    }
    $counter++;
}
answer Jun 17, 2013 by anonymous
0 votes

I think the rest after the if for the last is wrong. either do this: last if ($counter > 2);
or
if ( $counter > 2) { print if : . $counter . "n"; #could do print "if : $countern" as well last;}

answer Jun 17, 2013 by anonymous
Similar Questions
0 votes

I routinely generate rows of tab-separated data like this;

my @array = ( "boris", "natasha", "rocky", "bullwinkle"); print join "t", @array, "n";

However this code inserts an extra tab between bullwinkle and the newline character. So when it is important I do this instead:print join "t", @array;print "n";
I suppose you could put both statements on a single line. Is there a simpler/faster way to generate this output: boristnatashatrockytbullwinklen?

+2 votes

I am trying to figure out how to get my sever to come back up to operation on a power failure. Right now it comes up and gives me three choices. I don't want the bloody choices I just want it to straight reboot so can run it headless!

Any help appreciated.

+1 vote

I am trying to figure out how to list the rpms in, say:

@base-x
or
@printing
or
@fedora-release-nonproduct

and so on.

Any help?

+1 vote

I'm looking for introductory to advanced examples of RESTful programming in Perl preferably with some good explanations and best practices.

...