Search code examples
perlundef

Assigning multiple values in perl, trouble with undef


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]);

Solution

  • 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'.