mikb has asked for the wisdom of the Perl Monks concerning the following question:

I'm writing a script that grabs its input from an Excel Spreadsheet. I've used ParseExcel a long time ago, but I know the basics. But the documentation contains this snippet in the Synopsis:
$sheet->{MaxRow} ||= $sheet->{MinRow}; foreach my $row ($sheet->{MinRow} .. $sheet->{MaxRow}) {
Pardon my ignorance, but I've never seen the '||=' construct used before - could some kindly soul explain what it achieves (extra points if you can explain it in this context :-) )

Replies are listed 'Best First'.
Re: Logical Assignment Op (with Spreadsheet::ParseExcel)
by kyle (Abbot) on May 17, 2007 at 20:45 UTC

    The ||= performs an assignment only when the lvalue is false. "$x ||= $y" is equivalent to "if ( ! $x ) { $x = $y }".

    In this case, if $sheet->{MaxRow} doesn't have a non-zero value, it takes the value of $sheet->{MinRow}.

      In this case, if $sheet->{MaxRow} doesn't have a non-zero value, it takes the value of $sheet->{MinRow}.
      But beware, Perl has a wider view of what constitutes a false value. The following values are all false:
      • undef
      • 0 (either as a number or string)
      • "" (the empty string)
      Everything else is true. This means that values such as "0.0" or "0e00" are true, not false.

      print "undef is ", ( undef ) ? "true\n" : "false\n"; print "0 is ", ( 0 ) ? "true\n" : "false\n"; print "'0' is ", ( '0' ) ? "true\n" : "false\n"; print "'' is ", ( '' ) ? "true\n" : "false\n"; print "' ' is ", ( ' ' ) ? "true\n" : "false\n"; print "'0.0' is ", ( '0.0' ) ? "true\n" : "false\n"; print "'0e00' is ", ( '0e00' ) ? "true\n" : "false\n"; __DATA__ undef is false 0 is false '0' is false '' is false ' ' is true '0.0' is true '0e00' is true

      I don't know the specifics of Spreadsheet::ParseExcel, so this may not relevant ;)