[newbie] scope of the variables

PERL

    Next

  • 1. Sorting a Hash of Arrays by an Element in the Array
    Hello all- I have seen many old questions where people ask if this can be done, and many responses where people claim it is not possible. However, I believe I have done it successfully and that it is quite easy: for my $key (sort {$hash{$a}->[0] <=> $hash{$b}->[0]} keys %hash) { print "$key\n"; } Am I missing something??? It looks as if it can be done to me. Thanks, Alf
  • 2. opendir and readdir vs glob iteration
    Hello All, Under what circumstances (and in what manner) would it be advantageous to use method A over method B? *NOTE: these are just very simple examples, my real question is would you ever want to use opendir and readdir? can one accomplish tasks with these that would not be possible with glob? A) opendir(TMPDIR, $tmp) or die "can't open $tmp: $!\n"; while ( my $file = readdir(TMPDIR) ) { print "$file exists.\n"; } B) print "$_ exists\n" for glob($tmp);
  • 3. How to modify a XML file using Perl?
    Hi, I'm trying to update an XML file using Perl, but he does not work: I'm trying to extract the value of the last tag and store it in the first tag. See below: From: <TroubleTicket> <TroubleID>12345</TroubleID> <Descr>No SYNCH</Descr> <SwitchID>HDLOPER</SwitchID> </TroubleTicket> To: <TroubleTicket> <TroubleID>HDLOPER</TroubleID> <Descr>No SYNCH</Descr> <SwitchID>HDLOPER</SwitchID> </TroubleTicket> Here are the syntaxes i'm using: my(@records) = $xp->findnodes( 'TroubleTicket' ); foreach my $record ( @records ) { $record-> find('SwitchID')-> string_value = $record-> findvalue('TroubleID'); } Anyone would have any idea about how to modify a node value? Thanks, Yann
  • 4. Using CGI and GD modules
    test.cgi script shown below is adapted from the "CGI programming" book (chap.13). There's no problem with installation of GD module and generation of PNG file. However, on the web, it gives the following error. Is this a script error, or apache2 configuration error? ============================ Server error! The server encountered an internal error and was unable to complete your request. Error message: Premature end of script headers: test.cgi ============================ $ cat test.cgi use CGI; use GD::Graph::bars; $cgi = new CGI; $g = new GD::Graph::bars; @data = ( [qw(A B C D E F)], [qw(1 2 3 4 5 6)] ); $g->set( x_label => 'X', y_label => 'Y', title => 'TITLE', show_values => \@data ); $graph = $g->plot(\@data); print $cgi->header( -type => 'image/png', -expires => '-1d' ); binmode STDOUT; print $graph->png; ============================ Any help would be greatly appreciated. James

[newbie] scope of the variables

Postby news2003 » Wed, 01 Oct 2003 23:35:39 GMT

Hi all,


I am trying to create a module. and I have a question about the scope
of the variables.



lets say,

use strict;


sub one {

    my ($rvalue) = @_;   # here I define a variable

    for my $i (0..$#$rvalue){   # here I define a local 
                                # variable $i and I use it

        # do something
    }

}


sub second {

    my ($rvalue) = @_;   # on this second sub $rvalue 
                         # is a new one or I carry it
                         # as the first one

    
    for my $i (0..$#$rvalue){ # now the same case, $i was
                              # already defined and if the
                              # scope is just its
                              # own subsroutine, now this
                              # $i is something copletely
                              # new. Am I right?

      # do something else
   }
}


 # Thanks for your help
 # John

Re: [newbie] scope of the variables

Postby tadmc » Wed, 01 Oct 2003 23:54:45 GMT





None of the variables in your module code below will be visible
in the "use"ing program, they are all "lexical variables".

Learn all about Perl's two separate systems of variables at:

   "Coping with Scoping":

       http://www.**--****.com/ 



                                                    ^^^^^
                                    ^^^^^^^^

(I can't say "for" for "foreach". I reserve "for" for for(;;)   :-)


In Perl, local() has to do with _package_ variables, which are 
a form of _global_ variable, so it is confusing to use "local" 
to mean "local".   :-)  or should it be  :-( ?

You have defined a _lexical_ variable.

Lexical variables (my) always get you a completely new variable,
new memory allocated and all.

So, yes, $i will be visible only within the body of the foreach() block.

When the (foreach) block exits, $i will cease to exist.




You are right.


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

Similar Threads:

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


Hello,

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

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

4 def func
5   log.debug "a statement" # error is reported here when func is called
below
6  # some code
7 end
8
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?

Thanks.

2.newbie ?: expand variable within a variable

Hello!

Pardon me for this trivial question.
Is there a way to expand a perl variable with in a variable?
i.e. when I read a line "$line" from an input file,
   say the line in text(xml) file is like:
	$t:references([@CONTROLLER_TYPE = 0]/@$c) in ....,
when I print this line with print "$line", I want the variables $t and
$c in the above line to be expanded in the output.

In the code segment given below, the last case of the switch i.e.
print "$line"  literally prints $t and $c with out expanding them.

while (<IFH>) {
   my  $line = $_;
   SWITCH: for ($line) {
	/<TableDef[ 	]*name/i &&
	  do {$line =~ /(")(\w+)/; $t = $2; last;};	# set $t
	/<ColumnDef[ 	]*name/i &&
	  do {$line =~ /(")(\w+)/; $c = $2; last;};	# set $c
	/<RuleDef/i &&
	  do {$line =~ /(")(\w+)/; $rule = 1; last;};	# set rule
	/<\/RuleDef/i	&&
	  do {$line =~ /(")(\w+)/; $rule = 0; last;};	# unset rule
	/[aA-zZ]+/ &&	
	  do {print "$line" if $rule == 1; last;};
	}
}

Thanks in advance for any help!

Kris

3.scope of the variable?

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

In test.pm I have following:

#BEGIN OF THE TEST.PM
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);

….
….

#END OF THE TEST.PM

In test2.pm I have following:

#BEGIN OF THE TEST2.PM
package test2;

use strict;
use warnings;

….
#  How to test::dbaccess ??

#END OF THE TEST2.PM


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

Thanks,
Bogumil

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
 XXXX@XXXXX.COM 


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 72 guest