in reply to How can I read a line of text from a file into an array?
On the other hand if you need to use the file as it is, and if you know it will always have exactly four key-value pairs in the format you have given, this code will allow you to parse it into a hash.key1,value1 key2,value2 key3,value3 key4,value4
It ain't elegant or flexible, but it will satisfy your immediate need. If there are going to be spaces after the commas or other interesting things, that can be dealt with in this approach. But at a certain point, you would need to consider a more robust approach (i.e. a CSV module from CPAN). Which would be a bit of overkill just to grab four key-value pairs.open HANDLE, 'testhash.txt' or die "Can't open: $!"; my $data = <HANDLE>; close HANDLE; chomp $data; my %hash = $data =~ /'([^,]+),([^']+)', '([^,]+),([^']+)', '([^,]+),([^']+)', '([^,]+),([^']+)'/x; # demo use of the hash to access results foreach my $key (keys %hash) { print "$key $hash{$key}\n"; }
|
|---|