in reply to use simple scalar names to point to specific array elements

If you want named elements, use a hash instead.

my %hash = ( myvar => 3, name => 'Ovid', ); print $hash{name};

If the order of elements is important, you could use Tie::Hash::Indexed or something similar.

In any event, I would be careful about wanting to alias one variable to another. This can result in "action at a distance" problems and those can be hard to debug.

Finally, if you always know which index you wanted to access by name, you could try a constant:

use constant NAME => 2; print $array[NAME];

However, if you really, really want to be evil and alias a variable to an array element, then you can do the following. How this works is an exercise left to the reader :)

#!/usr/bin/perl use warnings; use strict; my @array = qw( foo bar baz ); my $var = alias_to(\@array, 1); print $var; sub alias_to { $_[0]->[$_[1]] }

Cheers,
Ovid

New address of my CGI Course.

Replies are listed 'Best First'.
Re: Re: use simple scalar names to point to specific array elements
by sauoq (Abbot) on Dec 05, 2003 at 20:58 UTC
    How this works is an exercise left to the reader :)

    Well, it doesn't actually work at all.

    $ perl -le 'sub alias_to { $_[0]->[$_[1]] } my @x = (1,2,3); my $z=ali +as_to(\@x,1); print $z; $z=42; print $x[1]' 2 2
    All it does is return the value of the array referenced in $_[0] at the index $_[1]. The aliasing of sub args isn't helping like you think it is.

    -sauoq
    "My two cents aren't worth a dime.";
    

      Silly me. Typing something from memory when I know how bad my memory is. Here's a correct version (which was cheerfully misremembered from Damian Conway):

      #!/usr/bin/perl use warnings; use strict; use Data::Dumper; use vars '@var'; my @array = qw( foo bar baz ); *var = alias_to(@array[1,2]); print Dumper \@var; $var[1] = 'silly me'; print Dumper \@array; sub alias_to { \@_ }

      Cheers,
      Ovid

      New address of my CGI Course.

        That's better. (And aliasing a slice is a nice twist on the theme.) But the OP wanted to be able to use simple scalars. Here's a modification that will do the trick:

        #!/usr/bin/perl use warnings; use strict; use vars qw( $alias ); sub alias_to { \$_[0] } my @array = qw( foo bar baz ); *alias = alias_to( $array[1] ); print "alias: $alias\n"; $alias = 'QUUX'; print "array: @array\n";
        It's really nothing more than a convenience function to do exactly the same thing as I suggested in my original answer in this thread. Looking at it, I'm not even sure it's that convenient. I think *alias = \$array[1]; is perfectly clear, and it doesn't require me to go check what the alias_to() sub actually does.

        -sauoq
        "My two cents aren't worth a dime.";