In this case your best bet would be to declare my (@array1, @array2) before the for loop if you want them to be available to your subroutines.
You are not having a problem with
undef, you are having a problem variable scoping.
As others have mentioned, you should be using strict - you said it won't help you solve the problem, but how can you solve the problem when you clearly don't understand what the problem is? Using strict will help you figure out what the problem is so you can at least look in the right direction.
Here's what I used to test your code:
#!/usr/bin/perl
use strict;
foreach my $item ('top', 'heavy', 'fool') {
my (@array1, @array2);
a_function($item);
print "@array1\n";
print "@array2\n";
}
sub a_function {
my $item = shift;
push @array1, 'crap';
push @array2, 'dumb';
}
This gave me errors like this:
Global symbol "@array1" requires explicit package name at ./test_loop.
+pl line 18.
Global symbol "@array2" requires explicit package name at ./test_loop.
+pl line 19.
Execution of ./test_loop.pl aborted due to compilation errors.
This clearly tells me that the subroutine is looking for global variables. Declaring them as
my inside a loop doesn't create global variables. So moving them to the top, like this, works fine:
...
my (@array1, @array2);
foreach my $item ('top', 'heavy', 'fool') {
...
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.