in reply to read multiple record data and populate in a new data stucture

This appears to do what you want:

#!/usr/bin/perl use warnings; use strict; use Data::Dumper; my ( $number, %accounts ); while ( <DATA> ) { chomp; if ( /^A,/ ) { ( undef, $number, my @fields ) = split /,/, $_, -1; @{ $accounts{ $number } }{ qw/ surname firstname job balance / + } = @fields; } elsif ( /^B,/ ) { my $transaction = ( split /,/ )[ 1 ]; push @{ $accounts{ $number }{ transactions } }, $transaction; } } print Dumper \%accounts; __DATA__ A,01,Newton,Issac,Physics, 5.6 B,144.56 B,1034.65 B,12.23 A,34,Einstein,Albert,Physics,12.22 B,2346.89 B,876.23 B,7656.81 B,745.21 B,25.63 B,89.56 B,7789.23 A,78,Feynman,Richard,Physics,-17.34 B,7412.36 B,2589.35 B,95.32 B,12.85 B,789.68

Replies are listed 'Best First'.
Re^2: read multiple record data and populate in a new data stucture
by fseng (Novice) on Jun 30, 2009 at 02:34 UTC
    Thanks jwkrahn. You are a legend.But I dont really understand a few places. what does this mean
    ( undef, $number, my @fields ) = split /,/, $_, -1;
    why do u use undef? I understand u r spliting the records with "," and what is $_, and -1, what do they do here?

      new at Perl myself but I couldn't see that anyone had answered your query "what is $_?".

      $_ is one of Perl's built-in variables - it is the default variable (i.e. what's currently being input or matched) and frequently if not explicitly set it will be assumed.

      These pairs are all the same: (these examples are from perlvar (http://perldoc.perl.org/perlvar.html)

      $_ The default input and pattern-searching space. The following pairs are + equivalent: while (<>) {...} # equivalent only in while! while (defined($_ = <>)) {...} /^Subject:/ $_ =~ /^Subject:/ tr/a-z/A-Z/ $_ =~ tr/a-z/A-Z/ chomp chomp($_)

      It's a very important variable to get your head around so do ask in the Chatterbox if you're unsure. (at least that's what I would do).

      This reply wasn't addressed to me, but here is an explanation for you:

      undef as an lvalue is one way of "throwing away" a value from the right hand side of the "=". This is actually very similar to the way that 'C' does it with an input format statement.

      my @a = (1,2,3,4,5); (undef, my @b) = (@a); print "@b\n"; #prints: 2 3 4 5 (the 1 is gone)
      Perl has another way, a "list slice" and I prefer this in my Perl code to the 'C' way. For example to "get rid" of the "2":
      my @a = (1,2,3,4,5); my @b = @a[0,2..4]; print "@b\n"; #prints: 1 3 4 5
      As far as the third parameter to split being -1, I see no reason for this at all as this means "no limit", the default. There are reasons to "limit" the number of things returned from split(), but I don't see it here.
      my $text = "1 2 3 4 5 6"; my @tokens = split(/\s+/,$text,2); foreach (@tokens) { print "$_\n"; } #prints: 1 2 3 4 5 6
      The above code limits the split to 2 things.