Others in this node have outlined the technique, but I'd like to present the concept in the context of a working example:

#!/usr/bin/perl -w use strict; use Data::Dumper qw(Dumper); my %hash; while (my $line = <DATA>) { next unless my ($id, @row) = $line =~ /^(\d+) (\w+) (\S+) (\w+) (\w+)$/; @{$hash{$id}}{qw(name email title date)} = @row; } print Dumper(\%hash); __DATA__ 1 merlyn merlyn@perlmonks.org saint today 2 tilly tilly@perlmonks.org saint today 3 tye tye@perlmonks.org saint today 4 jcwren jcwren@perlmonks.org saint today

This will iterate over the file handle, and attempt to match the $line with a regex. (You'll note that I changed the regex slightly to work with the data) If there is no match, then it will skip over the line. If there is a match, it will assign to a hash slice underneath $hash{$id}. It's the equivalent of:

my %hash; my %account; @account{ qw(name email title date) } = @row; $hash{$id} = \%account;

One advantage of the first example is that you are doing it in a single step, without using any 'Synthetic' Code.


In reply to (dkubb) Re: (2) Hash asignement with RE and map() by dkubb
in thread Hash asignement with RE and map() by bobione

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.