Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: Creating CSV term document matrix from a hash stored in multideminsional array

by stevieb (Canon)
on Mar 03, 2017 at 19:13 UTC ( [id://1183590] : note . print w/replies, xml ) Need Help??


in reply to Creating CSV term document matrix from a hash stored in multideminsional array

This:

for my $i($#classArr) {

Does not increment $i like you think it does. Essentially, it loops only once, because $#classArr is only a single number; the last element number in the array.

You want something more like:

for my $i (0..$#classArr){

Which will put the current element number into $i on each iteration, starting from 0.

update: Or, more idiomatically (untested):

for my $class (@classArr){ for my $href (@$class){ for my $key (sort keys %$href){ print $csv "$key-- $href->{$key},"; } } }

Replies are listed 'Best First'.
Re^2: Creating CSV term document matrix from a hash stored in multideminsional array
by lobs (Acolyte) on Mar 03, 2017 at 20:02 UTC
    yea I changed it recently and its now:
    foreach my $subArr_ref(@classArr) { print "subArr_ref: ".@{$subArr_ref}."\n"; foreach my $hashRef(@{$subArr_ref}) { print "hashRef: ".$hashRef."\n"; foreach my $key (sort keys %{$hashRef}) { #print $csv $key.":".$hashRef->{$key}.","; print $csv "$key : ${$hashRef}{$key},"; } # foreach my $feat(@featureVector) { # print $csv $hashRef->{$feat}.","; # } print $csv $i."\n"; } }

      Did that work?

      Note I updated my original reply before you posted this update, but it would be more idiomatic Perl to rewrite it something like this (untested):

      for my $class (@classArr){ for my $href (@$class){ for my $key (sort keys %$href){ print $csv "$key-- $href->{$key},"; } } }
        No that didn't work I know the problem is when I pass the hash into the array it is always the same memory reference. Therefore when I access the array every hash reference will be the same and print out the same value.