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"; } }

In reply to Help me understand this idiomatic hash from array code by adhrain

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.