in reply to pushing multidimensional arrays

afalsename:

You've already received guidance to solve your problem. But I'm bored, so...

I first glued a bit more code to your example so I could try it out. (You'll get more (and frequently better) responses if you perform this step yourself. I frequently ignore requests where the author doesn't perform this step. But I'm bored this morning.)

Next, I corrected the problem giving me this:

my @data = ( [1 .. 3], [4 .. 6], [7 .. 9] ); norm(); print join(", ", @{$_}), "\n" for @data; sub norm{ $p=$#data; #I call the 100k x 3 array @data for($i=0;$i<=$p; $i++){ # iterates down @data $norm=(($data[$i][0])**2+($data[$i][1])**2)**(1/2); #calculate +s the norm $data[$i][3] = $norm; } }

Next, I added strict and warnings, and made a couple changes to clean things up:

#!/usr/bin/perl use warnings; use strict; my @data = ( [1 .. 3], [4 .. 6], [7 .. 9] ); norm(); print join(", ", @{$_}), "\n" for @data; sub norm{ my $p=$#data; #I call the 100k x 3 array @data for(my $i=0;$i<=$p; $i++){ # iterates down @data my $norm=(($data[$i][0])**2+($data[$i][1])**2)**(1/2); #calcul +ates the norm $data[$i][3] = $norm; } }

While reading your post, I noticed two things about your code: The first thing I noticed about your code is that your subroutine directly accesses global data. (That could be an artifact of your hacking the code down to the relevent bits, but I don't know for certain.) The second thing I noticed is that you're using a C-like for loop, which is just too much work.

The first item I wanted to address was to make the subroutine use a simpler for loop:

sub norm{ for(@data){ # iterates down @data my $norm=(($$_[0])**2+($$_[1])**2)**(1/2); #calculates the nor +m $$_[3] = $norm; } }

As you can see, it makes things a little easier to read. Then I decided to let you specify the array at the point you call it, like so:

#!/usr/bin/perl use warnings; use strict; my @data = ( [1 .. 3], [4 .. 6], [7 .. 9] ); norm(\@data); print join(", ", @{$_}), "\n" for @data; sub norm{ my $ar = shift; for(@$ar){ # iterates down @data my $norm=(($$_[0])**2+($$_[1])**2)**(1/2); #calculates the nor +m $$_[3] = $norm; } }

Once all that was done, I noticed that $norm was used only once, so I removed it:

sub norm{ my $ar = shift; for(@$ar){ # iterates down @data $$_[3]=(($$_[0])**2+($$_[1])**2)**(1/2); #calculates the norm } }

Okay, now, I'm just about awake now, so I think I'll wrap this up and make myself some coffee and breakfast...

...roboticus

Update: Added readmore tags.