How to fill a hash from the products of a split

S

Steve

I am populating a hash from a text file
which consists of tab-delimited keys - values

Code fragment below


# if there is a file with titles, read it into hash
if (-e $image_file_path.$titlefile){
if (open (TITLEFILE, "<$image_file_path$titlefile")) {
while (<TITLEFILE>) {
chomp;
my @line = split /\t/;
$img_titles{$line[0]}=$line[1] || ' ';
}
}
}


It works, but I don't like it! Is there a way of putting the
products of the split straight into a hash without going via
an array ? One complication is the possibiity of a line in the
source file with no tab.

Thanks

Steve
 
T

Tore Aursand

I am populating a hash from a text file
which consists of tab-delimited keys - values

# if there is a file with titles, read it into hash
if (-e $image_file_path.$titlefile){
if (open (TITLEFILE, "<$image_file_path$titlefile")) {
while (<TITLEFILE>) {
chomp;
my @line = split /\t/;
$img_titles{$line[0]}=$line[1] || ' ';
}
}
}

First of all: Why do you check if the file exists in the first place, when
you could easily let 'open' deal with this?
It works, but I don't like it! Is there a way of putting the
products of the split straight into a hash without going via
an array ? One complication is the possibiity of a line in the
source file with no tab.

No complication at all, but I guess you would have to skip those lines
(ie. check if there's a \t somewhere in the string you're reading in);

my $filename = $image_file_path . $titlefile;
my %values = ();

open(TITLEFILE, $filename) or die "Couldn't open '$filename'; $!\n";
while (<TITLEFILE>) {
chomp;
next unless (/\t/);
my ($key, $value) = split(/\t/, $_, 2);
$values{$key} = $value;
}
close(TITLEFILE);
 
U

Uri Guttman

ga> what I would do:
ga> map{
ga> $img_titles{$1}=$2 if /(.*?)\t(.*)/;
ga> }<TITLEFILE>;

another map in void context!!!

and in this case not needed so no fighting.

use File::Slurp ;

my $text = read_file( 'whatever' ) ;

my %img_titles = $text =~ /^(.*?)\t(.*)/gm ;

not only is it cute, it is the fastest way to populate the hash.

uri
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,146
Messages
2,570,832
Members
47,374
Latest member
EmeliaBryc

Latest Threads

Top