adhrain has asked for the wisdom of the Perl Monks concerning the following question:

Noble Monks,

I seek your wisdom to guide me to understand this cool code I found in StackOverflow https://stackoverflow.com/questions/4156483/perl-create-a-hash-from-an-array

while I was translating a python script found on reddit (I find this kind of exercise very engaging and useful) https://www.reddit.com/r/ProgrammerHumor/comments/6mkac8/found_this_in_the_comment_on_rtinder/

The code creates an hash from an array, using as keys the elements of the array and as values their position in the array

my @header_line = ('id', 'name', 'age'); my %fields; @fields{@header_line} = (0 .. $#header_line); #result: %fields = { id => 0, name => 1, age => 2};

I skimmed the Camel book to no avail.


Here is the finished script, I'd also like to know your opinion on its quality

#!/usr/bin/env perl use strict; use warnings; use Algorithm::Permute; my @people = qw(Brian Carlos Dana Evan Farra); my $iter = new Algorithm::Permute(\@people); while (my @perm = $iter->next) { my %positions; @positions{@perm} = (0..$#perm); my $test = #Brian next to Dana abs($positions{Brian} - $positions{Dana}) == 1 #Dana not next to Evan && abs($positions{Dana} - $positions{Evan}) > 1 #Carlos on Dana's right && $positions{Carlos} - $positions{Dana} == 1 #one seat between Brian and Farra && abs($positions{Brian} - $positions{Farra}) == 2; if ($test) { print "@perm\n"; } }

Replies are listed 'Best First'.
Re: Help me understand this idiomatic hash from array code
by haukex (Archbishop) on Jul 11, 2017 at 18:59 UTC

    As tybalt89 already said, Slices (and perhaps the Range Operators if you haven't come across that yet).

    my @header_line = ('id', 'name', 'age'); @fields{@header_line} = (0 .. $#header_line); # is exactly equivalent to ($fields{id},$fields{name},$fields{age}) = (0,1,2);

      Here is the Light! Thank you both

Re: Help me understand this idiomatic hash from array code
by tybalt89 (Monsignor) on Jul 11, 2017 at 18:53 UTC

    see "Slices" in perldoc perldata

A reply falls below the community's threshold of quality. You may see it by logging in.
A reply falls below the community's threshold of quality. You may see it by logging in.