in reply to Two dimentional array

Two dimensional array of integers? Smells like C... :-)

package Array2D; use strict; use Carp; use constant sizeof_int => length pack 'i', 1337; sub new { my $class = shift; @_ == 2 or croak "must call ${class}::new with x, y dimensions"; my ($dx, $dy) = @_; $dx > 0 && $dy > 0 or croak "${class}::new : illegal x, y dimensions"; bless { dx => $dx, dy => $dy, buf => "\0" x ($dx * $dy * sizeof_int) }, $class; } sub get { my $ary = shift; my $class = ref $ary; @_ == 2 or croak "must call ${class}::get with x, y positions"; my ($x, $y) = @_; my ($dx, $dy) = @{$ary}{qw/dx dy/}; $x >= 0 && $y >= 0 && $x < $dx && $y < $dy or croak "${class}::get : subscripts out of range"; unpack 'i', substr ( $ary->{buf}, ($x + $y * $dx) * sizeof_int, sizeof_int ); } sub set { my $ary = shift; my $class = ref $ary; @_ == 3 or croak "must call ${class}::get with x, y positions and new value"; my ($x, $y, $val) = @_; my ($dx, $dy) = @{$ary}{qw/dx dy/}; $x >= 0 && $y >= 0 && $x < $dx && $y < $dy or croak "${class}::set : subscripts out of range"; substr ( $ary->{buf}, ($x + $y * $dx) * sizeof_int, sizeof_int, pack 'i', $val ); (); } 1;

Replies are listed 'Best First'.
Re^2: Two dimentional array
by algonquin (Sexton) on Sep 11, 2004 at 21:59 UTC
    Wow, looks good. I'm gonna experiment with it as soon as I get a chance. Thanks a lot.
      Wow, looks good. I'm gonna experiment with it as soon as I get a chance. Thanks a lot.

      :-) I wrote that short module just to show that multi-dimensional arrays can be done a la C, if you have nothing better to do. The only advantage is size - array elements occupy exactly four bytes (x86) which are packed into a pre-allocated string. There's no overhead introduced by individual elements or rows.

      Of course Perl has a native array type. Multi-dimensional arrays are not a fundamental type but they're easily constructed with references. See perldata, perldsc.

      The following code has serious side effects. Don't blindly cut and paste into your program (unless you like trouble).

      #!/usr/bin/perl my @ary = map {["${_}1", "${_}2", "${_}3"]} 'a'..'u'; $\ = "\n"; $" = $, = ","; split ($,), print map {$ary[$_[$_]][$_]} 0..$#_ for glob join $,, map {"{@{[0..20]}}"} 1..3;