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

Greetings to all,
I am having a problem when accessing the data from a PM file. Unless I actually put a value into the scalar there is NO data.
I have used require before with no problems . I dont understand what I have done that could break it.

Anyway this is what the print statement says. $smonth is ,$sday is 2, $syear is 2000
I was hoping that $smonth value would be "Jun" not "". Thanks for any help

Tim
#!/usr/local/bin/perl -w use strict; use diagnostics; use CGI qw(:standard); print header(); require schedule; my $s_month; my $s_day = 2 ; my $s_year = 2000; print "\$smonth is $s_month ,\$sday is $s_day, \$syear is $s_year\n"; ################### PM FILE ######################### #schedule $s_month = 'Jun'; $s_day = '21'; $s_year ='2004'; $week_1 = 'TEAM 1'; $week_2 = 'TEAM 2'; $week_3 = 'TEAM 3'; $week_4 = 'TEAM 4';

Replies are listed 'Best First'.
Re: problem with accessing PM file
by chromatic (Archbishop) on Jul 17, 2003 at 18:15 UTC

    When you declare the variables with my, Perl considers those values more important than the variables in the required file.

    use vars '$foo'; $foo = 'foo'; { my $foo = 'bar'; print "'$foo'\n"; }

    The quick solution is something like this:

    use vars qw( $s_month $s_day $s_year $week_1 $week_2 $week_3 $week_4 ); requre schedule; $s_day = 2; $s_year = 2000; print "\$smonth is $s_month ,\$sday is $s_day, \$syear is $s_year\n";

    A better answer may be using Exporter to export values from your schedule package into the namespace. Of course, looking at the values in schedule, I'm inclined to recommend:

    use vars qw( %s @weeks ); %s = ( month => 'Jun', day => 21, year => 2004, ); @weeks = ( 'TEAM 1', 'TEAM 2', 'TEAM 3', 'TEAM 4' );
Re: problem with accessing PM file
by ajdelore (Pilgrim) on Jul 17, 2003 at 18:15 UTC

    This is a problem of scope.

    When you declare my $s_month; you are scoping the variable to your main program.

    You need to get the value from $schedule::s_month, and you do not need to re-declare this in your main program at all:

    require schedule; print "\$smonth is $schedule::s_month ,\$sday is $schedule::s_day, \$s +year is $schedule::s_year\n";

    Your other option is to write a proper perl module that exports $s_month into the main program namespace. Be warned though, if you do this you will still clobber that value if you declare my $s_month in your main program.

    Check out perldoc perlmod for more information on writing a module.

    Updated: I needed to brush up on my vs. main::. Thanks for pointing that out, Zed.

    </ajdelore>

      Lexically scoped variables are separate from package variables, including those in the default package of main.
      $x = 2; my $x = 3; print $main::x, ' ', $x, "\n"; $main::x = 4; print $main::x, ' ', $x, "\n";
      produces:
      2 3
      4 3
      
      See MJD's Coping with Scoping