problem with variable scope

PERL

    Next

  • 1. Perl-mysql
    Hi, I would like to connect to a database stored at linux machine from my Windows machine. But I am unable to connect to the mysql server. Please help me regarding this issue. ************************************************************************ **************************** use DBI; $dbh = DBI->connect("DBI:mysql:employee:xxx.xxx.xxx.xx", 'root', 'abc123', { RaiseError => 1 } ); #do something here } $dbh->disconnect(); Thanks in advance -- siva
  • 2. Time::Local let me faint
    Hello,lists, Please see these two lines' output: [$ perl -Mstrict -MTime::Local -le 'print timelocal(0,0,0,31,8,2006)' Day '31' out of range 1..30 at -e line 1 $ perl -Mstrict -MTime::Local -le 'print timelocal(0,0,0,31,7,2006)' 1156953600 I translate the time of '2006-7-31 00:00:00' to unix timestamp,it's successful. But when I translate the time of '2006-8-31 00:00:00' to unix timestamp,it said '31 out of range'. I'm so faint that August doesn't have 31th day?Please tell me why this happen and how to resolve it. Thank you very much.
  • 3. replace multiple tokens
    I have the follows code perl -e ' @a=(q{a...x name=taga_1 #...d name=tagb_1 f...r name=tagc_1 xxnn}, q{h...e name=taga_4 t...g name=tagb_4 k name=tagc_4 nn}); $ndx = 0; foreach $ln (@a) { print "b4 = $ln\n"; $ln =~s/(name=.*)\d+/\1$ndx/g; print "af = $ln\n"; $ndx++ }' Which produces: b4 = a...x name=taga_1 #...d name=tagb_1 f...r name=tagc_1 xxnn af = a...x name=taga_1 #...d name=tagb_1 f...r name=tagc_0 xxnn b4 = h...e name=taga_4 t...g name=tagb_4 k name=tagc_4 nn af = h...e name=taga_4 t...g name=tagb_4 k name=tagc_1 nn I would like to produce: b4 = a...x name=taga_1 #...d name=tagb_1 f...r name=tagc_1 xxnn af = a...x name=taga_0 #...d name=tagb_0 f...r name=tagc_0 xxnn b4 = h...e name=taga_4 t...g name=tagb_4 k name=tagc_4 nn af = h...e name=taga_1 t...g name=tagb_1 k name=tagc_1 nn Any help will be greatly appreciated. jwm
  • 4. Print to new file for each results
    On 08/29/2006 06:32 PM, Ron McKeever wrote: > I am try to use part of someones elses code that creats the data file which prints out like this: > > ip|result|deptA|data > ip|result|deptB|data > ip|result|deptC|data > > My goal instead of having all the data in one big file is to loop this and create a file for each result. > So I would have a deptA.out file with deptA info then a deptB.out > file with dept b info and etc... > [...] Although this is very different from your program, it should give you the general idea: use strict; use warnings; use File::Slurp; use File::Spec::Functions; my @departments = q{ 192.168.14.0|88|Sales|Richard Throop 192.168.16.0|90|Accounting|Juliet Rosenblatt 192.168.20.0|91|Logistics|Mark Mane 192.168.24.0|94|Security|Marlon Johnson } =~ m/^\s*(.*)$/mg; # print join "\n", @departments; my $dir = catfile($ENV{HOME}, qw(tmp tmp)); foreach my $info (@departments) { my $fname = (split /\|/, $info)[2]; $fname = catfile($dir, $fname); print $fname, "\n"; write_file $fname, $info . "\n"; } __HTH__ :-)

problem with variable scope

Postby perlpra » Tue, 23 Oct 2007 23:31:25 GMT





Hi Gurus,



I have written a package as below.



__________________PACKAGE



package parseSite;

use strict;

use warnings;



sub new {

my $class = shift;

my $Input_file=shift;

bless
{InputFile=>$Input_file},$class;







}



sub Print_file

{



my ($self,$Category,$course_name,$Instructor,$videos)=@_;

print "$self\n";

print "$Category\n";

print "$course_name\n";

print "$Instructor\n";

print"$videos\n";

}





sub GET_Values

{

my $Rows;

my $cate;

my $self=shift;

print "$self->{InputFile}\n";

(open my $FILE_H '<', $self->{InputFile}) || die"cannot open the input
file";

while(<$FILE_H>)

{

next unless /(<div.*?<\/table><br><br>)/;

my @Rows=grep(/(<div.*?<\/table><br><br>)/,<$FILE_H>);

return(@Rows);


close $FILE_H;

}



1;



__________________PACKAGE





And I am using this package in the following script and trying to get the
some values.



--script





use strict;

use warnings;

use grepsite;



my $obj=grepsite->new("sample.txt");

my @rows=$obj-> GET_Values;

$obj-> Print_file(@rows);





--script



I am getting the following error,my Input file exists.





-----------------ERROR

Use of uninitialized value in concatenation (.) or string at grepsite.pm
line 37

.

InputFile in GET_TABLES Method is

parseSite=HASH(0x225f88)

1

Use of uninitialized value in concatenation (.) or string at grepsite.pm
line 26

.



Use of uninitialized value in concatenation (.) or string at grepsite.pm
line 27

.



Use of uninitialized value in concatenation (.) or string at grepsite.pm
line 28

.._-----------------------------ERROR.





I understand this is because the file $self->{InputFile} is not visible to
the method GET_Values



Whats the reason that this file is not visible to the GET_Values method.



Can somebody let me know where I am going wrong?



Thanks

PP.








<html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882" xmlns="http://www.w3.org/TR/REC-html40">

<head>
<meta name="Microsoft Theme 2.00" content="axis 011">
<meta http-equiv=Content-Type content="text/html; charset=us-ascii">
<meta name=Generator content="Microsoft Word 11 (filtered medium)">
<style>
<!--
/* Font Definitions */
@font-face
{font-family:Verdana;
panose-1:2 11 6 4 3 5 4 4 2 4;}
/* Style Definitions */
p.MsoNormal, li.MsoNormal, div.MsoNormal
{margin:0in;
margin-bottom:.0001pt;
font-size:12.0pt;
font-family:Verdana;
color:black;}
h1
{margin-top:12.0pt;
margin-right:0in;
margin-bottom:3.0pt;
margin-left:0in;
page-break-after:avoid;
font-size:16.0pt;
font-family:Arial;
color:black;}
h2
{margin-top:12.0pt;
margin-right:0in;
margin-bottom:3.0pt;
margin-left:0in;
page-break-after:avoid;
font-size:14.0pt;
font-family:Arial;
color:black;
font-weigh

Re: problem with variable scope

Postby pangj » Tue, 23 Oct 2007 23:50:35 GMT



Well,the first error I have noticed,you have lost a "}" in the code above.
Have you run `perl -c parseSite.pm` before you use it?

Re: problem with variable scope

Postby tom » Wed, 24 Oct 2007 00:03:30 GMT

On 10/22/07, Siva Prasad < XXXX@XXXXX.COM > wrote something resembling:


What are those variables used for?


I would have thought Perl would have warned you about having
unreachable code after the return(). Are you telling us that it
doesn't warn you about that? Nevertheless, the unreachable close()
isn't a problem; since $FILE_H is a lexical variable, it's auto-closed
when it goes out of scope. So I'd either put the close() before the
return(), or omit it altogether.



Which one is line 37? We can't see that piece of the puzzle, but you
can. You probably have a utility program that will show line numbers
(the cat utility generally has a -n option), or one that will easily
add or remove them (most programmer's text editors can do this, or you
could even write a small Perl program to do it (Okay, the cat's out of
the bag now: Somebody's going to make it a one-liner for this, I know
it. Please, change the subject line to "[golf] add/remove line
numbers" when you post it.)).


What makes you conclude that? From my reading of your code, having
that problem should have given you the error message "cannot open the
input file". But you're showing us totally different error messages.

My best guess at the error is that you got fewer values back from
GET_Values than you expected, and you called Print_file with too few
parameters -- probably zero.

And you probably got fewer values back from GET_Values because you're
trying to parse something as complex as HTML using simple patterns. Do
you also try to pound nails with your fists and turn screws with your
thumbnails? Use real tools (i.e. modules from CPAN) to parse HTML, if
that's what you're really doing, and you'll find the work goes more
easily at the end of the day.

Good luck with it!

--Tom Phoenix
Stonehenge Perl Training

Re: problem with variable scope

Postby Jenda » Wed, 24 Oct 2007 01:39:28 GMT

From:	"Siva Prasad" < XXXX@XXXXX.COM >

use HTML::TableExtract;

Jenda
=====  XXXX@XXXXX.COM  ===  http://www.**--****.com/  =====
When it comes to wine, women and song, wizards are allowed 
to get drunk and croon as much as they like.
	-- Terry Pratchett in Sourcery


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.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

3.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


4.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 


5.Variable scope

Hi,

I thought that the code snip below should work but I am not getting 
my text into the the file. The file is created but it's empty.

Ideally I want to create the log file outside any sub routines so 
that $log to be available to any sub I have created and hence not 
scoped to any one sub routine.  

Is my understanding not correct here? Should I be doing this in 
another way?

Thanx,
Dp.



#!/bin/perl

package Images;

 use strict;
 use warnings;
 use vars qw($log);

 $| = 1;
 our $log;
 my $logpath = 'mylog.txt';
 open($log,">>$logpath") or die "Can't append to $logpath: $!\n";


sub mysub {

my $var = 'Hello';
print $log "Starting mysub with val\n";

}

6. Local Scope Variables

7. Help with Variable Scope, Regular Expressions

8. extra constructor calls, inefficent loop variable scope?



Return to PERL

 

Who is online

Users browsing this forum: No registered users and 83 guest