0

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?

1
  • Can you show a few sample calls to this subroutine? I'm having a hard time picturing what you're looking for. Commented May 25, 2019 at 16:11

1 Answer 1

3

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.

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

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.