6

I have this code that works

my @new = keys %h1;
my @old = keys %h2;

function(\@new, \@old);

but can it be done without having to declare variables first?

function must have its arguments as references.

Nikhil Jain
  • 8,232
  • 2
  • 25
  • 47
Sandra Schlichting
  • 25,050
  • 33
  • 110
  • 162
  • 2
    Because you can't really "just try it" without knowing what to try? – cHao Apr 08 '11 at 10:38
  • She could at least have tried to replace @new and @old with the expressions on the RHS. Then, if perl complained, she could have asked why and how to prevent it. – Ingo Apr 08 '11 at 10:48
  • 2
    (1) Who's to say she didn't try it? If it were that easy, yeah, i'd be with you -- but it's not. (2) Personally, when i find myself trying random combinations of syntax in the hopes one will work, i'm *already lost* and probably should have asked for help sooner. (3) I doubt she (or anyone with a job to get done) cares why `function(\keys(%h1), \keys(%h2))` doesn't work -- just that it doesn't. Her goal is still clear, and not muddied by the tortured syntax of a thousand useless tries. (4) She came with a clear question and a problem that's not exactly easy to google. She has my upvote. – cHao Apr 08 '11 at 12:12
  • @cHao - I agree with you on most points. Though, if one seeks help it is always a good idea to indicate what one has tried already. Apart from that, best help is IMHO to help someone to help him- or herself in the future. – Ingo Apr 09 '11 at 09:10

2 Answers2

7
use strict;
use Data::Dumper;

my %test = (key1 => "value",key2 => "value2");
my %test2 = (key3 => "value3",key4 => "value4");

test_sub([keys %test], [keys %test2]);

sub test_sub{
 my $ref_arr = shift;
 my $ref_arr2 = shift;
 print Dumper($ref_arr);
 print Dumper($ref_arr2);
}

Output:

$VAR1 = [
          'key2',
          'key1'
        ];
$VAR1 = [
          'key4',
          'key3'
        ];
Nikhil Jain
  • 8,232
  • 2
  • 25
  • 47
6
function([ keys %h1 ], [ keys %h2 ]);

From perldoc perlref:

A reference to an anonymous array can be created using square brackets:

$arrayref = [1, 2, ['a', 'b', 'c']];

Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378