naturalsciences has asked for the wisdom of the Perl Monks concerning the following question:
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:
will post errors#!/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]|";} } } }
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.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.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: scoping problems
by hdb (Monsignor) on Jun 03, 2013 at 11:16 UTC | |
by naturalsciences (Beadle) on Jun 03, 2013 at 11:30 UTC | |
by AnomalousMonk (Archbishop) on Jun 03, 2013 at 14:47 UTC | |
by FloydATC (Deacon) on Jun 03, 2013 at 17:39 UTC | |
by hdb (Monsignor) on Jun 03, 2013 at 11:33 UTC | |
by naturalsciences (Beadle) on Jun 03, 2013 at 11:19 UTC | |
Re: scoping problems
by moritz (Cardinal) on Jun 03, 2013 at 12:08 UTC | |
by sundialsvc4 (Abbot) on Jun 04, 2013 at 23:58 UTC | |
by naturalsciences (Beadle) on Jun 07, 2013 at 08:46 UTC |
Back to
Seekers of Perl Wisdom