in reply to How can I read a line of text from a file into an array?

Okay, here's a more perlish, robust solution that will handle any number of key-value pairs. This code plays nice and spells out each step:
open HANDLE, 'testhash.txt' or die "Can't open: $!"; my $data = <HANDLE>; close HANDLE; chomp $data; my %hash; foreach my $pair (split /'/, $data) { next if $pair eq ''; # empty 'item' before first comma next if $pair =~ /^,$/; # throw away commas between pairs my ($key, $value) = split /,/, $pair; $hash{$key} = $value; } # demo use of the hash to access results foreach my $key (keys %hash) { print "$key $hash{$key}\n"; }
Or for a compact solution using the same logic. You could replace everything after the chomp with: my %hash = map {split /,/} grep !/^,$/, split /'/, $data;

Replies are listed 'Best First'.
Re: Re: How can I read a line of text from a file into an array?
by fenners (Beadle) on Jul 17, 2001 at 19:53 UTC
    Brilliant! That's helped enormously, thanks. Now for the real file which has several hundred lines and 10 key value pairs :)
      In that case (and you may already have this worked out) if you are building one great big hash, the main code would look something like:
      open HANDLE, 'testhash.txt' or die "Can't open: $!"; my %hash; for my $data (<HANDLE>) { chomp $data; foreach my $pair (split /'/, $data) { next if $pair eq ''; next if $pair =~ /^,$/; my ($key, $value) = split /,/, $pair; $hash{$key} = $value; } } close HANDLE; # do stuff with entire hash here
      Or if you are doing something with the hash line-by-line:
      open HANDLE, 'testhash.txt' or die "Can't open: $!"; for my $data (<HANDLE>) { chomp $data; my %hash; foreach my $pair (split /'/, $data) { next if $pair eq ''; next if $pair =~ /^,$/; my ($key, $value) = split /,/, $pair; $hash{$key} = $value; } # do interesting things with one-line %hash here } close HANDLE;
        Bless you Brother!