Here's just a
Tim Toady that simulates a file parser that reads the lines one by one into variables corresponding to each record's parameters (Full name, address, phone number) and then splits these around a semi-colon. It defines a counter
$counter that is incremented at the end of each record and appended to the hash key.Note that you don't need a blank line to separate the records since this code assigns each line it reads to a parameters in each record in tandem ..
Check Tutorials->References and perldsc to delve deeper into the world of advanced data structures in Perl.
#!/usr/local/bin/perl
use strict;
use Data::Dumper;
my %hash;
my $counter = 0;
until(eof(DATA)){
chomp (my $fullName = <DATA>);
my ($name, $val1) = split /\s+:\s+/,$fullName;
chomp (my $homeAddr = <DATA>);
my ($addr, $val2) = split /\s+:\s+/,$homeAddr;
chomp (my $phoneNo = <DATA>);
my ($phone, $val3) = split /\s+:\s+/,$phoneNo;
$hash{"user".++$counter} = {$name=>$val1, $addr=>$val2, $phone
+=>$val3};
}
print Dumper(\%hash);
__DATA__
FullName : User1
Home Address : 111 address lane
Phone : 555-555-5555
FullName : User2
Home Address : 222 address lane 2
Phone : 777-777-7777
$VAR1 = {
'user1' => {
'Phone' => '555-555-5555',
'Home Address' => '111 address lane',
'FullName' => 'User1'
},
'user2' => {
'Phone' => '777-777-7777',
'Home Address' => '222 address lane 2',
'FullName' => 'User2'
}
};
Update: Added more clarifications...
Excellence is an Endeavor of Persistence.
A Year-Old Monk :D .
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.