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

From the code below how do I create a temp array and pass to the addHost function, I use qw but can not seem to pass it as a reference the second call to addHost works correctly but I dont want to have to create an array each time.

my %getSSO; sub addHost($$) { print $_[1] . "\n"; $getSSO{$_[0]} = $_[1]; } my @a = ('apple','orange','choco'); addHost('aklia700',qw(carrot lunch)); addHost('aklia701',\@a); Useless use of a constant in void context at ./getAppXML line 31. lunch ARRAY(0x8103170) aklia701 apple orange choco aklia700 Can't use string ("lunch") as an ARRAY ref while "strict refs" in use +at ./getAppXML line 26.

Replies are listed 'Best First'.
Re: Basic Perl passing a temp array
by Enlil (Parson) on Nov 11, 2004 at 00:12 UTC
    change this line:
    addHost('aklia700',qw(carrot lunch));
    to
    addHost('aklia700',[qw(carrot lunch)]);
    have a look at perldoc perlref (what you are wanting is an anonymous array)

    -enlil

Re: Basic Perl passing a temp array
by Anonymous Monk on Nov 11, 2004 at 00:11 UTC
    Just worked it out
    addHost('aklia700',qw(carrot lunch));
    Reading the Oreilly books did it :)
Re: Basic Perl passing a temp array
by revdiablo (Prior) on Nov 11, 2004 at 17:29 UTC

    I would go the other route. Rather than making your caller create an array reference, have your subroutine do it:

    sub addHost { my $host = shift; print "$host\n"; $getSSO{$host} = [ @_ ]; } # now this will work as is addHost('aklia700', qw(carrot lunch)); # and it's also slightly simpler when you have a named array my @a = qw(carrot lunch); addHost('aklia700', @a);

    Update: fixed bug in subroutine. Old code was shifting after the anonymous array had been constructed.