narashima has asked for the wisdom of the Perl Monks concerning the following question:

Revered Monks,

I have a file in the following format:
A, B, C
D,E,F
G, H,I

The hash I want to create from this file should have the first element as in each row as its key and the 2 other elements as the corresponding value. eg. $hash{'A'}= "B,C"

I am able to do this using the conventional aprroach i.e creating an array first and then creating a hash.

However, I want to slurp this and split the data directly into a hash using map function.

Any suggestions?

thanks!

Replies are listed 'Best First'.
Re: question:File to hash using map
by holli (Abbot) on Jan 26, 2007 at 15:26 UTC
    %hash = map { s/ //g; /(\w),(.+)/; $1=>$2 } <HANDLE>;


    holli, /regexed monk/
Re: question:File to hash using map
by Zaxo (Archbishop) on Jan 26, 2007 at 15:32 UTC

    Or

    my %hash = map { chomp; split ',', $_, 2 } <$fh>;

    After Compline,
    Zaxo

      This does not work!

      Data dumper returns:
      $VAR1 = 'A'; $VAR2 = 'B,C'; $VAR3 = 'D'; $VAR4 = 'E,F'; $VAR5 = 'G'; $VAR6 = 'H,I';
        Hi narashima,

        Zaxo's solution actually does work.  I think you've made a mistake in the way you pass the data to Data::Dumper.

        You need to pass a reference to the hash, not just the hash itself.

        Try this:

        use strict; use warnings; use Data::Dumper; # Pretend that I've already read the file into @lines ... my @lines = ( 'A, B, C', 'D,E,F', 'G, H,I', ); # Zaxo's solution my %hash = map { chomp; split ',', $_, 2 } @lines; # View the data (use a *reference* to the hash, though!) printf "Data => %s\n", Dumper(\%hash);

        which correctly outputs the following...

        Data => $VAR1 = { 'A' => ' B, C', 'D' => 'E,F', 'G' => ' H,I' };

        s''(q.S:$/9=(T1';s;(..)(..);$..=substr+crypt($1,$2),2,3;eg;print$..$/
Re: question:File to hash using map
by johngg (Canon) on Jan 26, 2007 at 15:38 UTC
    You could do this

    use strict; use warnings; use Data::Dumper; my %hash = map { $_->[0] => join q{,}, @$_[1, 2] } map { chomp; [ split m{\s*,\s*} ] } <DATA>; print Dumper \%hash; __END__ A, B, C D,E,F G, H,I

    The output

    $VAR1 = { 'A' => 'B,C', 'D' => 'E,F', 'G' => 'H,I' };

    Cheers,

    JohnGG

Re: question:File to hash using map
by leocharre (Priest) on Jan 26, 2007 at 16:16 UTC
    You could also do this.. Your text.conf:
    --- A: - B - C D: - E - F G: - H - I
    And in your readin.pl:
    #!/usr/bin/perl -w use YAML; use Smart::Comments '###'; my $data = YAML::LoadFile('text.conf'); ### $data
    Your output:
    ### $data: { ### A => [ ### 'B', ### 'C' ### ], ### D => [ ### 'E', ### 'F' ### ], ### G => [ ### 'H', ### 'I' ### ] ### }

    YAML rocks