简体   繁体   中英

How can I pass an array resulting from a Perl method by reference?

Some XML::LibXML methods return arrays instead of references to arrays.

Instead of doing this:

$self->process_items($xml->findnodes('items/item'));

I want to do something like:

$self->process_items(\$xml->findnodes('items/item'));

So that in process_items() I can dereference the original array instead of creating a copy:

sub process_items {
    my ($self, $items) = @_;
    foreach my $item (@$items) {
        # do something...
    }
}

I can always store the results of findnodes() into an array and then pass the array reference to my own method, but let's say I want to try a reduced version of my code. Is that the correct syntax for passing the method results or should I use something different?

Thanks!

EDIT:

Now suppose I want to change process_items() to process_item() so I can do stuff on each element of the referenced array using a for loop. Something like:

$self->process_item($_) for ([ $xml->findnodes('items/item') ]);

This doesn't work as process_item() is executed only once because a single value is passed to the for loop (the reference to the array from findnodes() ). What's the proper way of using $_ in this case?

sub  do_something {
    (1, 2, 3, 4);
}

print [ do_something ];

This give me an array ref.

EDIT:

so, in your case, that would be:

$self->process_items([ $xml->findnodes('items/item') ]);

in which case, $self->process_items gets an arrayref. Similarly, if you wanted to make a hashref out of the return value of a function, you would put { and } around the return value.

EDIT 2:

As for your second question, for() takes an array, so, instead of doing for([ my_list ]) you would do for( @{ [ my_list ] } ) . @{} generates an array from a list. ${} produces a scalar from a scalar-ref.

You can't do a for against an arrayref because it only sees one thing, the arrayref itself, not the contents. You'll have to pass a reference to each item if you want to work that way, using something like:

map {$self->process_item(\$_)} $xml->findnodes('items/item');

sub process_item {
  my $item = shift;
  $item = $$item;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM