slicks1 slicks1 - 4 months ago 8
Perl Question

perl not saving variable value outside of if clause

I am a newbie to perl. Heres my issue:

my $monopentime;my $monopenper;my $monclosetime;my $moncloseper;my $monclosed;

if($monday ne "closed"){
my @monfields = split /-/, $monday;
my $monopen = $monfields[0];
my @monopenparts = split / /,$monopen;
my $monopentime = $monopenparts[0];
my $monopenper = $monopenparts[1];
my $monclose = $monfields[1];
my @moncloseparts = split / /,$monclose;
my $monclosetime = $moncloseparts[0];
my $moncloseper = $moncloseparts[1];
my $monclosed=0;
print $monopentime;
} else {
my $monopentime="1";
my $monopenper="AM";
my $monclosetime="1";
my $moncloseper="AM";
my $monclosed=1;
}
print $monopentime;


If you notice I have two print statements, one inside the
ne clause
and one outside the
if else
. when i print the variable
inside
the clause it prints the data but when I print outside the
if else
clause i get nothing.

Like I said im fairly new to perl what is the issue? I set my variables outside the clause too

Answer

my creates a new variable. Inside the if, you want to assign to the existing variable, so drop the my.

my ( $monclosed, $monopentime, $monopenper, $monclosetime, $moncloseper ); 
if ($monday eq "closed") {
    $monclosed    = 1;
    $monopentime  = "1";
    $monopenper   = "AM";
    $monclosetime = "1";
    $moncloseper  = "AM";
} else {
    $monclosed = 0;
    my ($monopen, $monclose) = split /-/, $monday;
    ( $monopentime,  $monopenper  ) = split ' ', $monopen;
    ( $monclosetime, $moncloseper ) = split ' ', $monclose;
}

print "$monopentime\n";

I cleaned up the code at the same time.

  • Avoided some needless temporary vars.
  • Used the list form of my to improve readability.
  • Avoided a needless negation in the condition (by swapping the "then" and "else" blocks).
  • Used split ' ' instead of split / / for increased robustness. (These are not equivalent.)
  • Improved indenting and spacing.
  • Moved $monclosed to the front/top. It seemed more natural.
Comments