Multiple assign to previously defined variables in Perl

183 views Asked by At

How to assign return values to previously declared variables in Perl? Is there a way to do something like this:

use strict;
use warnings;
my ($a, $b, $c) = first_assign();
 # let's say $a = "a", $b = "b", $c = "c"

($a, $b, $c) = second_assign();

# let's say we expect them to be "aa", "bb" and "cc" correspondingly

In this case all these variables will be equal to ''. So, is there some special way to assign to many previously declared at once?

1

There are 1 answers

1
Robby Cornelissen On

Just return a tuple from your assign methods:

use strict;
use warnings;

my ($a, $b, $c) = first_assign();
print "a = $a, b = $b, c = $c\n";

($a, $b, $c) = second_assign();
print "a = $a, b = $b, c = $c\n";

sub first_assign {
  return ('a', 'b', 'c');
}

sub second_assign {
  return ('aa', 'bb', 'cc');
}

This yields the following output:

a = a, b = b, c = c
a = aa, b = bb, c = cc