in reply to Running out of memory while running this for loop

I am also running out of memory before the loop completes.

What is your idea of $aref in that loop that bombs off? Is it an integer, or an array reference? What it the result of adding 1 to an array reference? or 2 ? What happens to an array (or array reference) if you index it with the result of that addition?

my $aref = []; print $aref,"\n"; print $aref + 1,"\n"; print $aref + 2,"\n"; print "mem: ",qx{ps -o vsz= $$}; $aref[$aref +2] = "foo"; print "mem: ",qx{ps -o vsz= $$}; __END__ ARRAY(0xf5dba0) 16112545 16112546 mem: 28964 mem: 154844

By converting the hexadecimal address of $aref to integer - this is what happens if you add an integer to it - and using it then as an index, you extend @data and pre-allocate slots, each containing a NULL value. If the address of $aref is high enough, your program hits the memory limit of your machine.

perl -le'print map{pack c,($-++?1:13)+ord}split//,ESEL'

Replies are listed 'Best First'.
Re^2: Running out of memory while running this for loop
by Ppeoc (Beadle) on Nov 01, 2015 at 21:57 UTC
    Yes! You are right. Thank you for catching that error. I was adding index value to array reference. How can I change my for loop to make it work?

      The "Perlish" way to iterate element-by-element over an array is:

      c:\@Work\Perl\monks>perl -wMstrict -le "my @array = qw(zero one two three); ;; for my $element (@array) { print qq{element '$element'}; } " element 'zero' element 'one' element 'two' element 'three'
      If each "element" of  @array is actually an array reference, you might then need to iterate in turn over the referenced array in similar fashion:
      c:\@Work\Perl\monks>perl -wMstrict -le "my @array = ( [ 1, 2, 3, ], [ 'v' .. 'z' ], [ qw(one two) ], ); ;; for my $arrayref (@array) { for my $element (@$arrayref) { printf qq{'$element' }; } print ''; } " '1' '2' '3' 'v' 'w' 'x' 'y' 'z' 'one' 'two'
      Please see perldsc for more info and examples.


      Give a man a fish:  <%-{-{-{-<

        Thank you so much! I now understand what I was doing wrong. Got it to work with the following piece of code
        for my $i ( 2033 .. $#data ) { if (($i-$n)%6267== 0) { $color = $data[$i][0]; $order= $data[$i+1][0]; $shape = $data[$i+3][0]; $name = $data[$i+4][0]; } print $out_ph1 $predata,",", $color,"," ,$order,"," ,$shape,", +" ,$name,","; for my $j ( 4 .. $#{ $data[$i] } ) { print $out_ph1 $data[$i][$j],"\_"; } print $out_ph1 "\n"; }
        Thank you monks!