Dennis Gray" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]
> I've googled all over the place and yet to come up with an example that
> would help this newbie do what he wants to do. I have a text file in the
> following format:
>
> 1 value1
> 2 value2
> 3 value3
> 4 value4
> ...
> 30 value 30
>
> I can load it into an array quite easily but how can I load it into a hash?

Hi Dennis.

Are you sure you want a hash? If the keys are 1 .. 30 as you show
then surely an array is better? Anyway, the program below should help you.

Cheers,

Rob



use strict;
use warnings;

my %hash;

while (<DATA>) {
  my ($key, $val) = split;
  $hash{$key} = $val;
}

use Data::Dumper;
print Dumper \%hash;

__DATA__
use strict;
use warnings;

my %hash;

while (<DATA>) {
  chomp;
  my ($key, $val) = split ' ', $_, 2;
  $hash{$key} = $val;
}

use Data::Dumper;
print Dumper \%hash;

__DATA__
1 value1
2 value2
3 value3
4 value4
30 value 30

**OUTPUT

$VAR1 = {
          '30' => 'value 30',
          '1' => 'value1',
          '2' => 'value2',
          '3' => 'value3',
          '4' => 'value4'
        };




-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to