0

Hello - This is my first perl scripting try.
I am trying to read a file into a hash so i can track it by id
the file looks like this:

ID FILNAME SIZE

1 logfilename 346202741018308
2 logfilename 0261512802421464
3 logfilename 612262297692848
4 logfilename 3268022049187
5 logfilename 888755246426701
6 logfilename 378923465017564
7 logfilename 314595896654591
8 logfilename 827978858998073
9 logfilename 943690319071184

open(FILE, "/tmp/file.txt") or die("Unable to open file");
my %hash;
while (my $line=<FILE>){
chomp($line);
my ($id, $filename, $size) = split/\s+/, $line;
$hash{$id}{filename}= $filename;
$hash{$id}{size}= $size;
}

print "$hash{id}\n\n";

close(FILE); I guess I want my hash to look like this:

%hash_id {
id => $id,
name => $name,
size => $size,
}; I want the first be sure I have $ID has the key for each record
because there can actually be many files for each record.
I want to swap the filename field and the checksum field.
Later in the prog I plan to compare each id records checksum value
when i copy the files. my problem for the moment is simply
getting the records out of the file and into the hash (or array).
I made several attempts and read some threads here but still no luck.

2
Contributors
1
Reply
2
Views
5 Years
Discussion Span
Last Post by d5e5
1

I don't know what you mean by "there can actually be many files for each record" but I think you want an array of hash references. See http://perldoc.perl.org/perldsc.html

#!/usr/bin/perl;
use strict;
use warnings;
use Data::Dumper;

my @AoH;#Array of hash references
while(my $line = <DATA>){
    chomp($line);
    my ($id, $filename, $size) = split/\s+/, $line;
    push @AoH, {id => $id,
                filename => $filename,
                size => $size};
}

foreach(@AoH){
    print "id is $$_{id}, filename is $$_{filename}, size is $$_{size}\n";
}

__DATA__
1 logfilename 346202741018308
2 logfilename 0261512802421464
3 logfilename 612262297692848
4 logfilename 3268022049187
5 logfilename 888755246426701
6 logfilename 378923465017564
7 logfilename 314595896654591
8 logfilename 827978858998073
9 logfilename 943690319071184

This gives the following output:

id is 1, filename is logfilename, size is 346202741018308
id is 2, filename is logfilename, size is 0261512802421464
id is 3, filename is logfilename, size is 612262297692848
id is 4, filename is logfilename, size is 3268022049187
id is 5, filename is logfilename, size is 888755246426701
id is 6, filename is logfilename, size is 378923465017564
id is 7, filename is logfilename, size is 314595896654591
id is 8, filename is logfilename, size is 827978858998073
id is 9, filename is logfilename, size is 943690319071184
Votes + Comments
Nice example for Array of hashes
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.