Training, Open Source computer languages
PerlPHPPythonMySQLApache / TomcatTclRubyJavaC and C++LinuxCSS 
Search for:
Home Accessibility Courses Diary The Mouth Forum Resources Site Map About Us Contact
Passing several lists to a sub

Posted by enquirer (enquirer), 17 March 2005
How do I pass in several lists to a sub in Perl and avoid the contents of them all getting lumped together?

Posted by admin (Graham Ellis), 17 March 2005
In Perl,  you call subs with a list as their parameter - so if you simply provide a number of comma separated lists in the call then they'll all get combined into a single list ... not what you want much of the time.

The solution is to use the \ operator to pass the ADDRESS of each list into the sub; it makes the internal code in the sub slightly more complex, but it cures the problem.

Example:
Code:
#!/usr/bin/perl

#%% Passing several lists into a sub

# Passing several lists to a Perl sub

@breakfast = qw(sausage bacon eggs);
@lunch = qw(kurma, nan, rice, dhansak);
@teatime = qw(water rest);

# WRONG - The lists get combined into one list
# Then there's no way of keeping them apart within

printmen1 (@breakfast,@lunch,@teatime,("pizza","McDonalds"));

sub printmen1 {
       print "FIRST call - one long list\n";
       @igot = @_;
       print $#igot," @igot\n";
       }

# RIGHT - Passing references to lists
# Then they're separated internally

printmen2 (\@breakfast,\@lunch,\@teatime,["pizza","McDonalds"]);

sub printmen2 {
       print "SECOND call - a list of lists\n";
       @igot = @_;
       for ($k=0; $k<@igot; $k++) {
               @current = @{$igot[$k]};
               print "$k:... @current\n";
       }
}


Runs:

Code:
[localhost:~/marpl] graham% perl 2lp
FIRST call - one long list
10 sausage bacon eggs kurma, nan, rice, dhansak water rest pizza McDonalds
SECOND call - a list of lists
0:... sausage bacon eggs
1:... kurma, nan, rice, dhansak
2:... water rest
3:... pizza McDonalds
[localhost:~/marpl] graham%


Note too how I've used square rather than round brackets to pass in the address of anonymous list(s) ...



This page is a thread posted to the opentalk forum at www.opentalk.org.uk and archived here for reference. To jump to the archive index please follow this link.

You can Add a comment or ranking to this page

© WELL HOUSE CONSULTANTS LTD., 2014: Well House Manor • 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01144 1225 708225 • FAX: 01144 1225 899360 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho