The reason may not be very obvious here, but if you have several statements in the body of the if block, then you can make much more visually obvious what depends on the condition in the if statement, and what not:$tempdesc = $hashref->{price}; $tempdesc2 = $hashref->{title}; if ($tempdesc >= 55 && $tempdesc2 !~ /electric/) { print FH_OUTFILE "free_batteries"; } print FH_OUTFILE "\n";
With this, anyone can see clearly that the three print statements between the curlies should be executed only if the condition is met, while the last print statement after the closing curly will run anyway.if ($tempdesc >= 55 && $tempdesc2 !~ /electric/) { print FH_OUTFILE "free_batteries\n"; print FH_OUTFILE "something else\n"; print "A message displayed on the screen if the condition is satis +fied\n"; } print FH_OUTFILE "\n";
Besides that, I agree with what other monks have said: use meaningful variable names, use strict; and use warnings;, and declare your variables with the my keyword. Also use lexical file handles. So your full code could end up being something like that:
use strict; use warnings; # here the code where the $hashref is populated (or maybe it is actual +ly part of a hash of hashes or array of hashes, we don't know enough +details) open my $FH_OUTFILE, ">", "output.txt" of die "could not open the outp +ut file $!"; my $price = $hashref->{price}; my $item_name = $hashref->{title}; if ($price >= 55 and $item_name !~ /electric/) { print $FH_OUTFILE "free_batteries"; } print $FH_OUTFILE "\n"; # perhaps some code to close $FH_OUTFILE (if you're done at this point +)
In reply to Re^3: If statement issue from a Noob
by Laurent_R
in thread If statement issue from a Noob
by tomdee27
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |