There's more than one way to do things | |
PerlMonks |
Re: calling subroutine inside loop - ERROR - subroutine executes only onceby Discipulus (Canon) |
on Dec 24, 2014 at 08:19 UTC ( [id://1111283]=note: print w/replies, xml ) | Need Help?? |
hello kaushik9918 and welcome. Your code is full of strange constructs and even if i'm not a master, i can suggest you some more perlish Perl. First a slightly modified version of your code: with this code the output is: Firstly onother way to get array filled with lines from a file:
then declare your var within the loop without juggling with $_:
More on when you call your subroutine you pass no argguments to it but you modify a global variable inside it. is not the safer way:
Now the chdir-path part: when you deal with path is better have an absolute one to use. In fact assuming you run your original code frome the dir /var/tests you get, as the first item of the array is processed, chdir AAA and if it is succesful you now are in /var/tests/AAA in the next iteration you try to go in /var/tests/AAA/BBB while you probably want /var/tests/BBB. Better would be to record the starting directory using the core Cwd module and concatenate the path using this base, as in:
This probably works as you wanted, but is still no safe Perl: when dealing with paths you need to be sure to the right thing possibly for every OS you can encounter. And concatenate paths with '/' can also be annoying. The core File::Spec is handy in this case:
You type some chars more but you can be sure to do the right thing and have a more robust code. HtH L*
There are no rules, there are no thumbs.. Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.
In Section
Seekers of Perl Wisdom
|
|