Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"

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

by dkubb (Deacon)
on Jul 04, 2001 at 06:49 UTC ( #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 saint today 2 tilly saint today 3 tye saint today 4 jcwren 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?

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

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (4)
As of 2022-12-08 02:55 GMT
Find Nodes?
    Voting Booth?

    No recent polls found