Passing two arrays to a subroutine in Perl

This is something I stumbled upon today, I had no idea on how to pass more than one array to a subroutine without loosing the information correspondence. The key is to pass references to the subroutine instead of the array itself:


use strict;
use English;

sub genStr($$);
sub genFile($@);

my $str = genStr("hue", "huo");
my $language = "Portuguese";
my @strings = ("str1", "str2", "str3", "str4", "str5");
genFile($language, \@strings);

sub genFile($@)
{
    my ($language, $strings) = @_;
    print("Language: $language\n");
    foreach (@$strings)
    {
        print("$_\n");
    }
}

sub genStr($$)
{
    my $string = "<string name=\"$_[0]\">$_[1]</string>";
    return $string;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s