Hi, the scope of variables has been a problem for me as I'm writing my casual scripts.
For some reasons I have been having trouble accessing some of my variables (declared by "my")although they should be inside the block as I do see those.
Maybe some of you can show me what is wrong. I guess I am having some trouble understanding what a block is that could contain a declaration.
For example this script:
#!/usr/bin/perl -w
use strict;
use warnings;
while (my $line=<>)
{
my @part=split(/\t/,$line);
my @saba=split(/\|/,$part[2]);
for(my $i=0;$i<@saba;++$i)
{
if ($saba[$i]!~m/unclassified/)
{(if $i==$saba){print "$_\n";}
else {print "$_|";}
}
else
{if ($i==$saba){print "unclassified_$saba[$i-1]\n";}
else {print "unclassified_$saba[$i-1]|";}
}
}
}
will post errors
syntax error at ./claskri.pl line 13, near "(if"
Global symbol "$saba" requires explicit package name at ./claskri.pl l
+ine 13.
syntax error at ./claskri.pl line 16, near "else"
Global symbol "$i" requires explicit package name at ./claskri.pl line
+ 17.
Global symbol "$saba" requires explicit package name at ./claskri.pl l
+ine 17.
syntax error at ./claskri.pl line 18, near "else"
Execution of ./claskri.pl aborted due to compilation errors.
I do not understand as I have declared my @saba already in encasing brackets. Should a loop inside those understand that I am trying to access the variable a "a level" up so to speak.
What I want is for all those loops to have access to variable @saba (or $saba in scalar context).
Right now it seems perl looks the innermost loops and checks that the saba is not declared locally within these (by not having "my" infornt them) - then demands it to be declared globally. What would be seem more normal for me would it to check one loop outside to check if it is declared in this - a sort of inheritance so to speak.
I do not dare do declare it inside these innermost loops as then it would probably remain empty == not assosiated with the actual saba form outer loop. And I do not want to declare it globally - as to eventually avoid colliding variable names.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|