Nissa
Nissa

Reputation: 215

How to process variable dimension array in Perl

I have a sub that takes in a reference of a multidimensional array and processes it.

The problem is, the underlying array may be 2D or 3D, or a 2D array with up to two fields that is a reference to a 1D array.

Is it possible to detect the dimension of the array, so that I can handle all these cases within this sub? Or I have to write several subs to handle all different dimensions?

Upvotes: 0

Views: 65

Answers (1)

Mark Reed
Mark Reed

Reputation: 95267

As in most dynamic languages, arrays in Perl are only one-dimensional. You usually represent a two-dimensional array by having each element of the array be a reference to another array - so you effectively have an array of arrays. If each element of an inner array is also a reference to a third array, then you effectively have a three-dimensional array.

If you don't know ahead of time how deep your array goes, you can use the ref function to check an element to see if it's a reference; if it is, then dereference it to get another dimension out of your array and process it. If not, then expect it to be a leaf element of the array.

One potential gotcha is that Perl doesn't enforce any kind of structure on the arrays; different elements can be different types. Which means subarrays could exist alongside simple numbers or strings in the same array. It'd be up to the array-construction code to make sure that a single array doesn't mix and match dimensionalities.

Upvotes: 3

Related Questions