variable scope and use strict



  • 1. passing "#" into subroutine
    I find $commenttag prints out nothing, what's the problem? I have to escape pound....? open( my $FPM, '<', "inputfile.txt"); $lineM = <$FPM>; while (&Nextline($lineM, "#", "<Models>")) { $lineM = <$FPM>; } sub Nextline { my ($line, $commenttag, $pattern) = @_; print "C:$commentag"; print $pattern;<STDIN>; if ($line =~ /^$commenttag/) { return 1; } if ($line =~ /$pattern/) { return 0; } else { return 1; } }
  • 2.
    Tried this code get a server 500 error. Anyone know what's wrong with it? if $DayName eq "Select a Day" or $RouteName eq "Select A Route") { dienice("Please use the back button on your browser to fill out the Day & Route fields."); } Thanks, Ron

variable scope and use strict

Postby Rocky » Wed, 28 Apr 2004 21:46:17 GMT

I am trying to use strict all the time now.  I have a problem with the
following code.  When I use strict the value of $highest won't leave the
foreach construct.  I know this is by design but I cannot figure out how
make that variable available outside the loop.  Any advice?

Also if someone could tell me where to find perldoc regarding "use
strict;" or scoping in general I would appreciate it.

my $number = 1;
my $dir = "/etc/backup";
opendir DIR1, $dir;
my @files = readdir(DIR1);
closedir DIR1;
foreach my $filename (@files)
        push(@filenum, $1)  if ($filename =~ /^CUX(\d+)\.txt$/);
        #my $highest = (sort { $a <=> $b } @filenum)[-1];
        $highest = (sort { $a <=> $b } @filenum)[-1];
        $final = $highest + $number;
print "CUX00" . "$final" . ".txt\n";

Re: variable scope and use strict

Postby Tore Aursand » Wed, 28 Apr 2004 22:00:50 GMT

But you don't.  Your code doesn't use strict at all.  It doesn't use
warnings, either;

  use strict;
  use warnings;

Needless use of double quotes;

  my $dir = '/etc/backup';

Always check if 'open()' and 'opendir()' succeeds;

  opendir( DIR1, $dir ) or die "$!\n";


  if ( opendir(DIR1, $dir) ) {
      closedir( DIR1 );
  else {
      # Something bad happened; Error message in $!

You could always make sure that you have the correct set of files when you
first read them in with 'readdir';

  my @files = grep { /^CUX\d+\.txt$/ } readdir( DIR1 );

It seems to be that you're trying to find the filename which have the
highest number.  This could be done like this;

  opendir( DIR1, $dir ) or die "$!\n";
  my @files = sort { $a <=> $b } grep { /^CUX\d+\.txt$/ } readdir( DIR1 );
  closedir( DIR1 );

  print 'Highest valued filename: ' . $files[-1] . "\n";

I guess 'perldoc strict' would get you going.

Tore Aursand < XXXX@XXXXX.COM >
"War is too serious a matter to entrust to military men." (Georges

Re: variable scope and use strict

Postby Rocky » Wed, 28 Apr 2004 22:17:01 GMT

I usually put use strict; but didn't here so that the script would work
is this because the value of $dir does not contain another variable and
does not need to be interpolated?
The filename is returned to a korn shell script, but the filename is
highest + 1 so that the korn shell script can create the file and add
details about last night's backups.

I read the strict perldoc and that was good but I am still missing
thank you for your help.  

Re: variable scope and use strict

Postby Tad McClellan » Wed, 28 Apr 2004 22:17:02 GMT

   perldoc strict


   "Coping with Scoping":


    Tad McClellan                          SGML consulting
     XXXX@XXXXX.COM                    Perl programming
    Fort Worth, Texas

Re: variable scope and use strict

Postby Richard Morse » Wed, 28 Apr 2004 23:32:20 GMT

In article < XXXX@XXXXX.COM >,

I _think_ (although I'm not certain), you're asking how to make a 
variable available outside a loop.

Try this example:

use strict;
use warnings;

my $highest;
$highest = 0;
foreach (1 .. 9) {
   if ($_ > $highest) {
      $highest = $_;

print $highest, "\n";

The key point (if I understand your question) is to declare the variable 
before you enter the loop (I also initialized it to 0, so I didn't get a 
warning about uninitialized values being used in the comparison).  Then 
it remains available once you leave the loop.

One trick -- make sure you don't rescope the variable inside the loop 
(ie, don't use 'my $highest' inside the loop), because that would hide 
the original $highest from the statements inside the loop.



Re: variable scope and use strict

Postby Rocky » Wed, 28 Apr 2004 23:57:24 GMT

perfect.  Thank you

Re: variable scope and use strict

Postby David K. Wall » Thu, 29 Apr 2004 00:00:19 GMT


Yes. It's a stylistic choice; like proper indentation, it can make your 
code easier to read. Using single quotes indicates to the reader that 
there's no need to look for variable interpolation, and conversely, 
double quotes are a signal to look for variable interpolation.

It's not a major issue in this case, but using appropriate quoting is a 
good habit to develop.

Re: variable scope and use strict

Postby Tore Aursand » Thu, 29 Apr 2004 01:52:48 GMT

As David already has pointed out (in an excellent way): Yes.

You mean before you _read_ from the directory?  No.  That doesn't make
sense, does it?

  opendir( DIR, $dir ) or die "$!\n";
  # Read the contents of <DIR>
  closedir( DIR );

No problem adding 1 to the value extracted above.

Tore Aursand < XXXX@XXXXX.COM >
"What we see depends mainly on what we look for." (Sir John Lubbock)

Re: variable scope and use strict

Postby gml4410 » Thu, 29 Apr 2004 03:34:51 GMT

In article < XXXX@XXXXX.COM >, Rocky < XXXX@XXXXX.COM > writes:
   Why do you remember everything, when all you want is the maximum? 
And reading in all file names just to process them sequentially isn't

 my $number = 1;
 opendir DIR1, $dir or die "opendir: $!\n";
 my $highest;    # Now defined outside of the loop, so visible after it
 while (1) {
    my $filename = readdir(DIR1);
    last if (not defined $filename);
    if ($filename =~ /^CUX(\d+)\.txt$/)) {
       $highest = $1 if ($1 > $highest);
 closedir DIR1 or die "closedir: $!\n";
 my $final = $highest + $number;
 print "CUX00" . "$final" . ".txt\n";

--------- Gordon Lack ---------------  XXXX@XXXXX.COM   ------------
This message *may* reflect my personal opinion.  It is *not* intended
to reflect those of my employer, or anyone else.

Re: variable scope and use strict

Postby Tore Aursand » Thu, 29 Apr 2004 03:57:46 GMT

I don't like this code at all.  Why do you call readdir() in scalar
context when there's no need to?  Do you fear that there are too many
files to fit in memory?  If so, you could at least have dropped that
'while (1)' thing;

  while ( my $filename = readdir(DIR) ) {
      if ( $filename =~ /^CUX(\d+)\.txt$/ ) {
          $highest = $1;

I still prefer the other suggestion I had (in a previous posting), though;
Using 'sort' and 'grep'.

Tore Aursand < XXXX@XXXXX.COM >
"First get your facts; then you can distort them at your leisure."
 (Mark Twain)

Similar Threads:

1.newbie question about scope, variables, declarations of variables and option strict (as in perl)


I am trying to understand the syntax error I receive in a code similar to

1 require 'logger'
3 log =  #some other logger settings are ignored.

4 def func
5   log.debug "a statement" # error is reported here when func is called
6  # some code
7 end
9 #some code continues
10 func

When func is called, an error is reported on line-5 saying that undefine
local variable log etc. I understand that functions create scopes and log is
seen as local variable  which is not defined in that scope. As it is
qualified with no scope operator, interpreter thinks that it is local but
can not find definition of the log before it's usage but also in the
parameter list and I understand that. On the other hand, I can use log
without qualifying it with a scope symbol anywhere in the same file if it is
not in a function. I know that loops, if statements etc are built into the
language and do not create scope. Code blocks inherit the locals. So it is
meaningful that I can use it anywhere else. When I qualify log with $ as
$log, it becomes global and I no longer receive error. I have tried it
qualifying with @ etc. but the received the same error. What I am asking is,
what is scope of log?. What kind of variable is it? It is the local or
instance variable of what, Object? I know that func is private to the
Object. But what about log?  How  can  I  access it in a function without
making it global?

Is there a way to make variables local to a file as perl does with "my".

Is there a strict option that prevents unintended variable creation because
of typos. Is there a way force predeclaration of variables?


2.Global variables from a module, while using strict

3.scope of the variable?

Hello All,
I have following question regarding accessing variable from other module:

In I have following:

package test;

use strict;
use warnings;

# The object responsible for managing the database connections.
my $dbaccess = undef;

-somewhere else 
$dbaccess = new xxxx::xxx::DBAccess( %dbURL);



In I have following:

package test2;

use strict;
use warnings;

#  How to test::dbaccess ??


My question is how to access $dbaccess variable (object) defined and initialized in within module?


4.Variable scope in wanted function

Greetings All -

I am having some difficulty with a module that is using File::Find.  The
method is below.

The idea is to enter this method feeding it a file name and beginning
directory and then looking for all occasions of $file_name and push those
addresses into @a_files.  This works fine until I need to use FindPath again
during the same session.  What I'm finding is that while @a_files looses
scope within FindPath itself, it does not in ProcessFile.  In other words,
when I exit FindPath and come back into it later, @a_files is an uninitiated
array.  However when ProcessFile is called, @a_files has retained the values
it had from the last call to FindPath.

Am I making sense?

sub FindPath
    #- Var Declaration And Initialization
    my ($hr_self, $file_name, $file_path) = @_;
    # Array to fill with file paths
    my @a_files = ();

    # Search file_path for the file
    find(\&ProcessFile, $file_path);

    #- The Subroutine To Process Files And Directories
    sub ProcessFile
        {if ($_ eq $file_name){push (@a_files, $File::Find::name);}}

    # Return the paths found
    return @a_files;
    }   # end FindPath

Peace -
Ron Goral

5.comparing and contrasing two approaches to variable scope

Assuming you had a script configuration variable that was used numerous 
places in your script, further assume that you have "use strict;" in 
your perl script.

You could declare the variable "my" and pass that variable to any 
subroutines that needed it with @_.

Or you could declare that variable with "local" or some other "scope 
defining declaration" so that it would be available automatically in any 
and all subroutines called from the level you declared the var as "local"

My question concerns a little of form and a little of function

On the function front:

which approach is faster?  With one you need a

my ($arg1, $arg2...) = @_;

inside each subroutine which should take some time to execute.

(I apologize if the syntax isn't correct for the above line, I don't 
have my notes available and I'm questioning the use of the parenthesis, 
but you should be able to get the idea, which is all I'm after)

On the form front, Ive noticed that the scripts are not as readable for 
me, and by extension probably any other people who use my script.

What are your thoughts on choosing which approach to take?  I'm sure 
both are technically correct, but I'm sure there are places where one 
approach should be preferred over the other.

Rance Hall
System Administrator
Nebraska Turkey Growers
1-308-468-5711, ext. 106

6. problem with variable scope

7. Variable scope

8. Local Scope Variables

Return to PERL


Who is online

Users browsing this forum: No registered users and 88 guest