Question

Je souhaite renvoyer plusieurs valeurs d'un sous-programme Perl et les attribuer en masse.

Cela fonctionne de temps en temps, mais pas lorsqu'une des valeurs est 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 semble concaténer les valeurs, ignorant les éléments undef.Une mission de déstructuration comme en Python ou OCaml est ce que j'attends.

Existe-t-il un moyen simple d’attribuer une valeur de retour à plusieurs variables ?

Modifier:voici la façon dont j'utilise maintenant pour transmettre des données structurées.Le tableau @a doit être passé par référence, comme l'a suggéré MkV.

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]);
Était-ce utile?

La solution

Je ne sais pas ce que vous entendez par concaténation ici :

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

impressions

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

alors que:

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

tirages :

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

La seule différence est que $otherval est désormais undef au lieu de « zap ».

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top