in reply to Sub routines

All of your problems are related to not understanding lexical scope, lexical variables, and the concepts of outter scopes being masked by inner scoped variables of the same name.

There's no need to declare 'my @list;' on line 7 (ie, outside the loop). This lexical variable is masked by the version of @list that exists within the sub, and that's the only time you use that variable anyway.

Your declaration on line 8 of @records gets masked by the new @records declaration within the while() loop. Then when the loop terminates, you get the original @records back, empty because it is not the same variable you were using within the while() loop.

You're pushing onto @list a reference to @list. And then returning @list. Yet inside your sub @list will never have more than one element. If that's really what you want, just return \@list. But that's probably not what you really want anyway. You probably want @list to not be passing in and out of scope every time you call your sub. But what's not what you need. You need to use lexical scoping correctly.

@records will never contain more than one element at the end of each iteration of your while() loop. And then it passes out of scope and disappears.

Any lexical declared within your while() loop will cease to exist at the end of each loop iteration. So there is nothing to print from @records. The @records being used inside the while() loop is a different variable from @records declared outside the while loop.

As mentioned in other posts, it's a bad habit to absorb values into a subroutine without passing them explicitly. That even applies to lexical filehandles.

Your biggest challenge seems to be in gaining an understanding of lexical scoping. perlsub is a good first step in understanding. But I'd actually recommend you pick up a copy of Learning Perl, from Randall Schwartz. Most of the problems you're having will disappear after you read through that book.


Dave

Replies are listed 'Best First'.
Re^2: Sub routines
by velocitymodel (Acolyte) on Mar 31, 2011 at 14:20 UTC

    Thank you for your advice and help. I do have that book and I am slowly working through it. Thanks again.