The following code will give you the desired output:
#!/usr/bin/perl -w
use strict;
my %users;
my $username;
while (<DATA>) {
next if (/^\s*$/);
chomp;
if (/^Username\:\s+([A-Z]+)\s+Owner\:\s+(.*)$/) {
$username = $1;
$users{$username}{realname} = $2;
}
elsif (s/^(Last Login\:\s*)//) {
($users{$username}{i}, $users{$username}{ni}) = split /,/, $_;
}
else {
die "line invalid - $_, $!\n";
}
}
foreach my $user (keys %users) {
print
"$user,$users{$user}{realname},$users{$user}{i},$users{$user}{
+ni}\n";
}
__DATA__
Username: JANDERSON Owner: JOE ANDERSON
Last Login: 14-JAN-2002 08:14 (interactive), 4-MAR-2002 17:09 (non-in
+teractive)
Username: PBARRETT Owner: PAUL BARRETT
Last Login: 18-JAN-2006 08:14 (interactive), 24-MAR-2005 17:09 (non-i
+nteractive)
Comments:
- Your main problem is that you weren't correctly assigning to the hash. Instead of $login_times{ni} you need something like $login_times{$user}{ni]
- There is no need to quote your hash elements if they don't contain whitespace (it just makes the code more confusing)
- I re-named your hash as %users, so it makes more sense
- Your username pattern match was capturing all the whitespace following the username. If you can assume that all usernames will be uppercase letters only, then you could re-write that as /^Username\:\s+([A-Z]+)\s+Owner\:\s+(.*)$/
I should also note that the above code is quite fragile, insofar as it assigns the $username when it reads the first line, and then assumes that the username is the same when it gets to the second line. There are probably much better ways to go about this, which no doubt some other monks will point out :)
Cheers,
Darren :)
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.