in reply to Ternary in void context
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"
Found in /usr/lib/perl5/5.8.0/pod/perlfaq6.pod What's wrong with using grep or map in a void context? The problem is that both grep and map build a return list, regardless of the context. This means you're making Perl go to the trouble of building a list that you then just throw away. If the list is large, you waste both time and space. If your intent is to iterate over the list then use a for loop for this purpose. Found in /usr/lib/perl5/5.8.0/pod/perlfaq8.pod What's wrong with using backticks in a void context? Strictly speaking, nothing. Stylistically speaking, it's not a good way to write maintainable code. Perl has several operators for running external commands. Backticks are one; they collect the output from the command for use in your program. The "system" function is another; it doesn't do this. Writing backticks in your program sends a clear message to the readers of your code that you wanted to collect the output of the command. Why send a clear message that isn't true? Consider this line: `cat /etc/termcap`; You forgot to check $? to see whether the program even ran correctly. Even if you wrote print `cat /etc/termcap`; this code could and probably should be written as system("cat /etc/termcap") == 0 or die "cat program failed!"; which will get the output quickly (as it is generated, instead of only at the end) and also check the return value. system() also provides direct control over whether shell wildcard pro- cessing may take place, whereas backticks do not.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Ternary in void context
by davido (Cardinal) on Nov 29, 2003 at 16:53 UTC |