0

I have a 2 dimensional array like this:

$map[0][0] = 'a';
$map[0][1] = 'b';
$map[1][0] = 'c';
$map[1][1] = 'd';

I want to pass only everything under $map[1] (by reference) to a subroutine. How to do that ?

0

3 Answers 3

4

Perl doesn't have multiple dimension arrays.

What you have is an array and each element of that array is a reference to another array. You might want to read up about Perl References since this is the way Perl allows you to build some very complex data structures.

Many people think of it as a multidimensional array, and you could treat it as such under certain circumstances. However, I prefer the -> syntax which reminds me that this is merely a reference to a reference.

$map[0]->[0] = 'a';
$map[0]->[1] = 'b';
$map[1]->[0] = 'c';
$map[1]->[1] = 'd';

Now, I can take the data structure apart:

  • @map: This is an array with two items in it, $map[0] and $map[1].
  • $map[0]->[]: This is a reference to another array. That array also has to items in it.
  • $map[1]->[]: This is another reference to yet another array. That array has two items in it.

Note that $map[1]->[] means that $map[1] contains an array reference. Thqt means you can pass $map[1] as your reference to that inner array.

mysub ($map[1]);

Here's a simple program:

#! /usr/bin/env perl
#
use strict;
use warnings;
use feature qw(say);

my @map;
$map[0]->[0] = 'a';
$map[0]->[1] = 'b';
$map[1]->[0] = 'c';
$map[1]->[1] = 'd';

mysub( $map[1] );

sub mysub {
    my $array_ref = shift;

    my @array = @{ $array_ref };  # Dereference your reference

    for my $index ( 0..$#array ) {
        say "\$map[1]->[$index] = $array[$index]";
    }
}

This prints:

$map[1]->[0] = c
$map[1]->[1] = d

Now, you see why I like that -> syntax although it's really completely unnecessary. It helps remind me what I am dealing with.

Sign up to request clarification or add additional context in comments.

Comments

1

You can send array reference,

sub mysub {
  my ($aref) = @_;

  # work with @$aref ..
}

mysub($map[1]);

Comments

1

Simply pass the scalar $map[1].

fn($map[1]);

sub fn
{
    my @loc_map_1 = @{ $_[0] };

Remember that perl doesn't have "real" 2 dimensional arrays. In your case map is an array that contains 2 references to arrays.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.