Home > database >  How can I pass a reference of an array defined as constant?
How can I pass a reference of an array defined as constant?

Time:04-08

I defined hash and array constants, When passing those to a function, I'll have to pass them as references. However I'm wondering what the correct syntax is.

Consider this example:

#!/usr/bin/perl
use strict;
use warnings;

use constant AC => qw(a b c);

sub f($)
{
    print "ref=", ref $_[0], "\n";
    print "$_\n" foreach (@$_[0]);
}

f(\AC);

When I run it I get:

ref=SCALAR
Use of uninitialized value $_ in concatenation (.) or string at /run/media/whatever/constref.pl line 10.

The Perl debugger prints C as an array:

13: f(\AC);
  DB<1> x AC
0  'a'
1  'b'
2  'c'
  DB<2> c

CodePudding user response:

AC is a reference to an array, not an array. Simply replace

f(\AC);

with

f(AC);

Note that the referenced array isn't constant, just the reference. Use Readonly to create an array that can't be modified.

CodePudding user response:

The only array in your code is @_ the array used to pass parameters into your subroutine. Your constant is a list, not an array. And you can't take a reference of a list.

I can think of three options for you.

  1. Don't pass a reference, just pass the constant. You need to lose the prototype on the subroutine (but I'm not sure what it's gaining you anyway):

    use constant AC => qw(a b c);
    
    sub f
    {
        print "ref=", ref $_[0], "\n";
        print "$_\n" foreach (@_);
    }
    
    f(AC);
    
  2. Make use of the fact that constants are actually subroutines and pass a reference to a subroutine instead:

    use constant AC => qw(a b c);
    
    sub f($)
    {
        print "ref=", ref $_[0], "\n";
        print "$_\n" foreach ($_[0]->());
    }
    
    f(\&AC);
    
  3. Switch to using a better constants library (like Readonly) instead.

  • Related