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

Good morning Monks!
Im having a slight problem matching the values of an array to the values of an AoAs.
I have an AoA, where the array contains records, and the records contain values, similar to this:
([a1v1,a1v2,a1v3,a1v4], [a2v1,a2v2,a2v3,a2v4], [a3v1,a3v2,a3v3,a3v4])
These records will have the same number of values but there can be any number of records.
I also have a 1 dimensional array, which contains a list of field names, e.g.
("f1","f2","f3","f4")
These obviously correspond to the record values. What I would like to do is simply print out the field name and then the field value, e.g.:
f1: a1v1 f2: a1v2 f3: a1v3 f4: a1v4 f1: a2v1 f2: a2v2 f3: a2v3 f4: a2v4 f1: a3v1 f2: a3v2 f3: a3v3 f4: a3v4
Im having a small problem with this! My code at the moment consists of the following:
for (my $x = 0; $x < $record_count; $x++) { foreach (@column_names) { print $_ . ": " . @$aref[$x] . "\n" unless $found; } }
I dont suppose there is anyone out there at this time in a morning to shed a bit of light on this?!
Thanks in advance, Steve

Replies are listed 'Best First'.
Re: match array values to AoA values
by BrowserUk (Patriarch) on Mar 11, 2005 at 02:57 UTC

    Something like this?

    my @a = ( [a1v1,a1v2,a1v3,a1v4], [a2v1,a2v2,a2v3,a2v4], [a3v1,a3v2,a3v3,a3v4], ); for my $rec ( @a ) { print join "\n", map{ ("f1","f2","f3","f4")[ $_ ] . ':' . $rec->[$_] } 0 .. 3; } f1:a1v1 f2:a1v2 f3:a1v3 f4:a1v4 f1:a2v1 f2:a2v2 f3:a2v3 f4:a2v4 f1:a3v1 f2:a3v2 f3:a3v3 f4:a3v4

    Examine what is said, not who speaks.
    Silence betokens consent.
    Love the truth but pardon error.
    Lingua non convalesco, consenesco et abolesco.
      BrowserUk

      What an earth is going on in that map!

      I'd very much appreciate a pointer or two as to what is happening.

      Thanks in advance,

      John

      Update:

      ("f1","f2","f3","f4")[ $_ ]

      It was this that threw me. The list is operating as an array. When $_ == 0 it produces "f1". Another snippet for the toolbox.

      Thanks again.

Re: match array values to AoA values
by Roy Johnson (Monsignor) on Mar 11, 2005 at 04:34 UTC
    For traversing arrays in parallel, see Algorithm::Loops 'MapCar'.
    use Algorithm::Loops 'MapCar'; my @aoa= map { my $a=$_; [map "A${a}V$_", 0..3] } 0..2; my @labels = ("f1","f2","f3","f4"); for my $rec (@aoa) { print MapCar(sub{"$_[0]: $_[1]\n"}, \@labels, $rec); }

    Caution: Contents may have been coded under pressure.
Re: match array values to AoA values
by chas (Priest) on Mar 11, 2005 at 03:14 UTC
    One possible way:
    @A=([a1v1,a1v2,a1v3,a1v4], [a2v1,a2v2,a2v3,a2v4], [a3v1,a3v2,a3v3,a3v4]); @names=("f1","f2","f3","f4"); for (my $x = 0; $x <= $#A; $x++) { for (my $y = 0; $y < 4; $y++) { print $names[$y]. ": " . $A[$x][$y ] . "\n"; } print "\n"; }

    chas
    (Update/comment: Probably not the nicest way, but basically fixing the main problem with your code.)