Please explain "and next"

Discussion in 'Perl Misc' started by Dave Saville, Jan 19, 2014.

  1. Dave Saville

    Dave Saville Guest

    Came across this today

    print "1 OK\n" and next unless (length $line[0]);

    Never seen that construct before. Is it just some perlish shorthand
    to get stuff on one line?

    TIA
     
    Dave Saville, Jan 19, 2014
    #1
    1. Advertisements

  2. See perldoc perlop "Logical And" and perldoc -f next.
    You should be able to figure it out.

    hp
     
    Peter J. Holzer, Jan 19, 2014
    #2
    1. Advertisements

  3. In this case, it's just a verbose and somewhat byzantine way to express

    print("1 OK\n), next unless length($line[0]);

    Generally, the so-called 'logical operators', (||, &&, //, and, or)
    don't evaluate their right-hand arguments if the value of the combined
    expression is already known after evaluating the left-hand
    argument. This implies they can be used for flow-control in the sense
    that code making up the right-hand argument will only be executed when
    executeing the code of the left-hand argument wasn't sufficient to
    determine the result of the expression. The line you quoted is a bad
    example because the 'next' isn't really executed conditionally because
    the print-statement always returns true. A better example could be
    something like

    $age >= 18 or die("Won't sell this to you.");
     
    Rainer Weikusat, Jan 19, 2014
    #3
  4. * Rainer Weikusat wrote in comp.lang.perl.misc:
    Actually, `print` returns a true value only if successful and it might
    have failed for any number of reasons, like a closed socket, a full hard
    disk, and other IO problems like that.
     
    Bjoern Hoehrmann, Jan 19, 2014
    #4
  5. But that's exceedingly unlikely because print just copies the output
    data into an internal buffer and I doubt that the intention behind the
    original code was to continue execution when print failed.
     
    Rainer Weikusat, Jan 19, 2014
    #5
  6. Στις 19/1/2014 17:02, ο/η Dave Saville έγÏαψε:





    use strict;
    use warnings;

    while (<DATA>) {
    chomp;
    my @line = split /,/;
    print "1 OK\n" and next unless (length $line[0]);
    print "id $line[1]\n";
    }

    __DATA__
    ,id00
    aaaaaaaaaa,id01
    bbbbbbbbb,id02
    cccccccc,id03
    ,id04
    ,id05
     
    George Mpouras, Jan 19, 2014
    #6
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.