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

Hi Monks

I am stuck on this that seemed simple, but I can not see it.
I need to return the values from this sub inside of a module. I am printing a Dumper of
the data but is coming empty, can anyone help me on this?

Here is a code sample to show what is going on:
# modulo accounts #!/usr/bin/perl use strict; use warnings; my $file = "test.txt"; my $accounts = account( file => $file, ); results( data => $accounts, ); sub account { ... return \@account; } sub results { ... my $results = \@data; return $results; } 1;

# script account.pl #!/usr/bin/perl use strict; use warnings; use Data::Dumper; use accounts; my $newdata = results(); print Dumper $newdata;
Thanks for the help!

Replies are listed 'Best First'.
Re: Returning data from a sub routine in a module.
by toolic (Bishop) on Apr 19, 2016 at 19:39 UTC
    You didn't show how you assigned anything to @data in your .pm file. When I fill @data, I get the expected output:
    sub results { my @data = 1..5; my $results = \@data; return $results; }
      I didn't because I just want to make sure I am calling the sub in the module from the perl script the correct way. I my code if I do a print Dump inside of the module's sub I get data but as I asked, from the Perl file it returns an empty value. So you are saying since you added data the code I posted is correct?
Re: Returning data from a sub routine in a module.
by stevieb (Canon) on Apr 19, 2016 at 19:54 UTC

    This really depends on how your files are set up. Here's an example using accounts.pm module file, and a script.pl file that uses it.

    Both files are in the same directory, so I use use lib '.'; so the script knows to look in the current directory for the module file. Then in the module file, I use Exporter to set things up so you can then import the results() sub properly from the module:

    accounts.pm module file

    package accounts; use strict; use warnings; require Exporter; our @ISA = qw(Exporter); our @EXPORT_OK = qw(results); sub account { my $file = shift; open my $fh, '<', $file or die $!; my @accounts = <$fh>; close $fh; chomp @accounts; return \@accounts; } sub results { my $file = shift; my $results = account($file); return $results; } 1;

    script.pl script file

    use strict; use warnings; use Data::Dumper; use lib '.'; use accounts qw(results); my $file = "accounts.txt"; my $newdata = results($file); print Dumper $newdata;

    accounts.txt file:

    a b c d e

    Output:

    $VAR1 = [ 'a', 'b', 'c', 'd', 'e' ];
      I see that you called account() from inside of results(), but I still have to pass my $file = "test.txt"; to account().

        I updated my post. The results() sub accepts a file name from the script, then it passes it to accounts() for processing, and then returns the results.