Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Array is empty when using if else condition

by kaka_2 (Sexton)
on Aug 28, 2014 at 10:46 UTC ( [id://1098850]=perlquestion: print w/replies, xml ) Need Help??

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

Hello Monks

I am not getting why i am getting an empty array when using if else condition.

i have a simple script as below.

#!/usr/bin/perl my $SP4binconfig = "/etc/SPECdaemons.list"; open (my $fh, '<', $SP4binconfig) or die "cant open the file : $!"; my @SPECores = <$fh>; close $fh; print "@SPECores";

this script print the array correctly. but when i use the same codes with If Else condition it does not and i cant figure out what is wrong with this

#!/usr/bin/perl my $SP4binconfig = "/etc/SPECdaemons.list"; if (-e $SP4binconfig) { open (my $fh, '<', $SP4binconfig) or die "cant open the file : $!"; my @SPECores = <$fh>; close $fh; } else { print "mmmmm"; } print "@SPECores";

Could someone help?

Replies are listed 'Best First'.
Re: Array is empty when using if else condition
by AppleFritter (Vicar) on Aug 28, 2014 at 11:39 UTC

    To expand on what flexvault said: you're using @SPECores as both a lexical and a global variable. The lexical declaration (my @SPECores) in your if() { ... } block shadows the global variable, so you're writing to the lexical variable, but when it goes out of scope at the end of the block, the global variable becomes visible again, and that's what you print.

    use strict; might've given you a clue here, BTW:

    Global symbol "@SPECores" requires explicit package name at 1098850.pl + line 17. Execution of 1098850.pl aborted due to compilation errors.

    Always use strict. It's your friend, and will catch many mistakes and potential sources of headaches for you.

      To expand, runrig's Use strict and warnings writeup is excellent reading and a jump off point for other commentary on error catching facilities offered in perl.
      Thank you both of you. I understand it now. -KAKA-
Re: Array is empty when using if else condition
by flexvault (Monsignor) on Aug 28, 2014 at 10:59 UTC

    kaka_2,

    my @SPECores = <$fh>;

    You must first define '@SPECores' before the 'if...else...'.

    Regards...Ed

    "Well done is better than well said." - Benjamin Franklin

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (2)
As of 2024-04-24 15:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found