tags:

views:

75

answers:

1

I want to return several values from a perl subroutine and assign them in bulk.

This works some of the time, but not when one of the values is undef:

sub return_many {
    my $val = 'hmm';
    my $otherval = 'zap';
    #$otherval = undef;
    my @arr = ( 'a1', 'a2' );
    return ( $val, $otherval, @arr );
}

my ($val, $otherval, @arr) = return_many();

Perl seems to concatenate the values, ignoring undef elements. Destructuring assignment like in Python or OCaml is what I'm expecting.

Is there a simple way to assign a return value to several variables?

Edit: here is the way I now use to pass structured data around. The @a array needs to be passed by reference, as MkV suggested.

use warnings;
use strict;

use Data::Dumper;

sub ret_hash {
        my @a = (1, 2);
        return (
                's' => 5,
                'a' => \@a,
        );
}

my %h = ret_hash();
my ($s, $a_ref) = @h{'s', 'a'};
my @a = @$a_ref;

print STDERR Dumper([$s, \@a]);
+6  A: 

Not sure what you mean by concatenation here:

use Data::Dumper;
sub return_many {
    my $val = 'hmm';
    my $otherval = 'zap';
    #$otherval = undef;
    my @arr = ( 'a1', 'a2' );
    return ( $val, $otherval, @arr );
}

my ($val, $otherval, @arr) = return_many();
print Dumper([$val, $otherval, \@arr]);

prints

$VAR1 = [
          'hmm',
          'zap',
          [
            'a1',
            'a2'
          ]
        ];

while:

use Data::Dumper;
sub return_many {
    my $val = 'hmm';
    my $otherval = 'zap';
    $otherval = undef;
    my @arr = ( 'a1', 'a2' );
    return ( $val, $otherval, @arr );
}

my ($val, $otherval, @arr) = return_many();
print Dumper([$val, $otherval, \@arr]);

prints:

$VAR1 = [
          'hmm',
          undef,
          [
            'a1',
            'a2'
          ]
        ];

The single difference being that $otherval is now undef instead of 'zap'.

MkV
Looks like I fixed something when simplifying my test case. I'll have to dig up the original in my reflog. Sorry.
Tobu