Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

(dkubb) Re: (2) Hash asignement with RE and map()

by dkubb (Deacon)
on Jul 04, 2001 at 06:49 UTC ( [id://93756]=note: print w/replies, xml ) Need Help??


in reply to Hash asignement with RE and map()

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://93756]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (2)
As of 2024-04-20 05:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found