Sunday 2 March 2014

Perl is Cool 3, Destructuring Assignment

Destructuring Assignment (DS, also known by other names like Multiple Assignment) is one of those features that after the first time you come across with it in one of the languages providing it (Python, Groovy, ES6...) you wonder why in hell other languages (C#, Java...) don't implement it. It's even harder to understand why it was left out of these languages when you find that it's not a new idea at all, and a language quite prior to them, Perl, features it. Indeed, Perl allows for some very interesting uses of this feature, let's take a look:

Assigning from an Array

This is the most well known use case of DS, It's massively employed in Perl for arguments assignment (given that a subroutine receives all its arguments in the @_ array), but we can also use it the other way around:

#function and parameters
sub format{
 my ($f1, $f2) = @_;
 ...
}
format("aa", "bb");

#function and return values
sub getBestFilms{
 return "Incendies", "Seven";
}
my ($film1, $film2) = getBestFilms();
Assigning from a Hash

This one is pretty interesting, and I had never seen it in other languages. You can easily assign values in a hash to different variables:

my %countries = (
 Asturies => "Xixon",
 Germany => "Berlin"
);

my ($astCity, $gerCity) = @countries{"Asturies", "Germany"};
($gerCity, $astCity) = @countries{"Germany", "Asturies"};
Create a Hash from 2 Arrays

Again, pretty interesting, and had never seen it before in any other language

my @people = ("Xuan", "Iyan");
my @cities = ("Uvieu", "Berlin");
my %peopleToCity;
@peopleToCity{ @people } = @cities;
foreach my $person (keys(%peopleToCity)){
 print $person . ": " . $peopleToCity{$person}. "\n";
}
Iterate a Hash

DS provides a very convenient way to iterate Keys and Values in one Hash

while ( my ( $person, $city ) = each (%peopleToCity) ) {
 print $person . ": " . $city. "\n";
}

Probably there are many more tricks/idioms in Perl involving DS, but so far these are the ones I can think of.

No comments:

Post a Comment