Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re^3: If statement issue from a Noob

by Laurent_R (Canon)
on Oct 04, 2017 at 20:37 UTC ( [id://1200689]=note: print w/replies, xml ) Need Help??


in reply to Re^2: If statement issue from a Noob
in thread If statement issue from a Noob

Still not rightly formatted, the print FH_OUTFILE "free_batteries" should be indented compared to the if statement:
$tempdesc = $hashref->{price}; $tempdesc2 = $hashref->{title}; if ($tempdesc >= 55 && $tempdesc2 !~ /electric/) { print FH_OUTFILE "free_batteries"; } print FH_OUTFILE "\n";
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:
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";
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.

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 +)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1200689]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (3)
As of 2024-04-19 15:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found