onegative has asked for the wisdom of the Perl Monks concerning the following question:

Howdy Monks,
I am having difficultly with user defined functions in that they return data but not when using strict pragma. How do you use strict correctly when defining your own functions and returning data. I have provided the code and it works if I comment out the use strict pragma. I read the definitions about strict pragma but I am just not getting it in terms of user defined function returning results.
Here is my code and many thanks for the help
#!/usr/local/bin/perl -w use Net::MySQL; use strict; sub get_all_records{ my $mysql = Net::MySQL->new( hostname => '', # Default use UNIX soc +ket database => 'RTSERVER', user => 'nco', password => 'xxxxxxxx' ); $mysql->query(q{SELECT * FROM RTSERVER.SITESCOPE}); my $a_record_iterator = $mysql->create_record_iterator(); my @db; while (my $record = $a_record_iterator->each) { push(@db, "$record->[0]:$record->[1]:$record->[2]:$record->[3] +:$record->[4]:$record->[5]:$record->[6]:$record->[7]"); } $mysql->close; return @db; } get_all_records(); my $count = 1; foreach my $item (my @db){ # THIS IS PROBLEM,DIFFERENT array print "Record #$count: $item\n"; $count++; }

Replies are listed 'Best First'.
Re: passing variables from user defined function when use strict
by FunkyMonk (Chancellor) on Aug 20, 2007 at 18:43 UTC
    A my variable can't be used outside of the block (the enclosing braces) in which it's declared. When a subroutine returns a value (or values), there has to be another variable to take up those values. In other words, your return @db needs the function call to be my @db = get_all_records()

    Note that the @db inside the function is completely different to the @db outside the function. It just happens to have the same name.

    dominus wrote a classic tutorial on this subject. See Coping with Scoping.

      Thanks and good reading...I was having a brian f@rt...
      I should have assigned the function to the array variable instead of expecting the @db to be the same variable...
      Thanks for your help...
Re: passing variables from user defined function when use strict
by akho (Hermit) on Aug 20, 2007 at 18:34 UTC
    my @db = get_all_records(); my $count = 1; foreach my $item (my @db){ print "Record #$count: $item\n"; $count++; }

    The @db inside the function and @db outside it are different and actually not related.