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

310426 is a reply I posted in regard to testing whether a file opened correctly. The following post says that the ternary, map and grep operators are bad to use in a void context. Can someone expound on "void context" doesn't open return a value on success or failure or am I missing something entirely? Can someone point me to some information about this or explain why this is bad

Thanks a ton guys,

Grygonos

Replies are listed 'Best First'.
Re: Ternary in void context
by The Mad Hatter (Priest) on Nov 29, 2003 at 14:54 UTC

    The ternary operator should be used to return a value. If you aren't making use of that return value and instead executing code (print in this case), then it is being used in void context. Using the ternary like so

    print (open(FH,"<".$log) ? "opened" : "unable to open $!"), "\n";

    would be using it correctly (i.e. not void context, it's returning the value to print).

    From perldoc -q "void context"

      As of Perl 5.8.1 (and confirmed in perldelta for 5.8.1), map is now smart enough to avoid creating that throw-away list if invoked in void context.

      So the efficiency issue in using map in a void context being gone (in Perl 5.8.1 and later), the remaining issue is that of style, clarity, and convention.

      grep, backticks, and the trinary operator are still examples of where a return-value is still generated regardless of context, and thrown away in void context.


      Dave


      "If I had my life to live over again, I'd be a plumber." -- Albert Einstein
Re: Ternary in void context
by Zaxo (Archbishop) on Nov 29, 2003 at 22:14 UTC

    The ternary operator can be an lvalue. In that case I believe it is in void context. I don't know of any problem with using it in void context as a shorthand if..else construct, either, though I dislike to do that. ($var ? $yes : $no) = some_sub();

    After Compline,
    Zaxo

      Lvalue context is not void context.

      $bar = 12; $bar; # void context; $bar = 13; # lvalue (not void) context $string = "foobar"; substr($string,0,3); # void context substr($string,0,3) = 're'; # lvalue (not void) context