I want to make a hash of arrays. I thought I was doing it correctly, but apparently I'm not. I expect a result like this:
10
a l
11
b m
Here's the code:
#!/usr/bin/perl
use strict;
use warnings;
my $filename = $ARGV[0];
my $outFilename = $ARGV[1];
open OUTFILE, ">", $outFilename or die $!;
open FILE, $filename or die $!;
my $id;
my $date;
while(<FILE>)
{
my $line = $_;
if($_ =~ /(.*?)\t+(.*?)\[/ ) {
$id = $1;
$date = $2;
print OUTFILE "$id\t$date\n";
}
my $key;
my $i;
my %HoA;
push @{ $HoA{$id} }, $date;
my $k;
foreach $k (keys %HoA) {
print "$k\n\t";
foreach (@{$HoA{$k}}) {
print " $_";
}
print "\n";
}
}
The input is like this:
10 a[
11 b[
12 c[
13 d[
14 e[
15 f[
16 g[
17 h[
18 i[
19 j[
20 k[
10 l[
11 m[
12 n[
13 o[
14 p[
15 q[
16 r[
17 s[
18 t[
19 y[
20 v[
But the output is sadly like this:
10
a
11
b
12
c
13
d
14
e
15
f
16
g
17
h
18
i
19
j
20
k
10
l
11
m
12
n
13
o
14
p
15
q
16
r
17
s
18
t
19
y
20
v
This confuses me because it looks like it is making more than one hash entry per key. What am I doing wrong here?
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.