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

I want to create function that will process multiple variables and return multiple arrays, something like this:
(@file, @file2) = getfile('file.txt', 'file2.txt');
Can anyone write an example of such sub ?
P.S. Number of variables passed to function may vary

Replies are listed 'Best First'.
Re: Multiple variables sub
by ikegami (Patriarch) on Feb 22, 2009 at 09:40 UTC

    It's impossible to do exactly that, since a sub can only return a list of scalars. The entire list would be assigned to @file.

    You could return array references, though.

    sub getfile { ... return ( \@file, \@file2 ); } my ($file, $file2) = getfile('file.txt', 'file2.txt'); for (@$file ) { ... } for (@$file2) { ... }
Re: Multiple variables sub
by ysth (Canon) on Feb 22, 2009 at 09:55 UTC
Re: Multiple variables sub
by ikegami (Patriarch) on Feb 22, 2009 at 23:26 UTC

    Number of variables passed to function may vary

    If each input and each output are independent as they appear, it's a bad design. Use a loop on the outside of the function, not inside.

    sub getfile { my ($qfn) = @_; open(my $fh, '<', $qfn) or die("Can't open \"$qfn\": $!\n"); <$fh> } my @files = ('file.txt', 'file2.txt' ); my @file_contents = map { [ getfile($_) ] } @files;

    The contents and the names and the contents are in parallel arrays, so it's still not optimal. Fix:

    sub getfile { my ($qfn) = @_; open(my $fh, '<', $qfn) or die("Can't open \"$qfn\": $!\n"); <$fh> } my @files = ('file.txt', 'file2.txt' ); my %file_contents = map { $_ => [ getfile($_) ] } @files;

    You can access the data as follows:

    for my $file (keys %file_contents) { print("File $file:\n"); my $content = $file_contents{$file}; for my $line (@$content) { print($line); } print("\n"); }
Re: Multiple variables sub
by Bloodnok (Vicar) on Feb 22, 2009 at 23:16 UTC
    As both ysth & ikegami have said, you can't return more than one list from a sub since perl flattens them into a single list - see Recipe 10.9 in the CookBook.

    A user level that continues to overstate my experience :-))