in reply to Re: use simple scalar names to point to specific array elements
in thread use simple scalar names to point to specific array elements

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.";

Replies are listed 'Best First'.
Re: Re: Re: use simple scalar names to point to specific array elements
by Ovid (Cardinal) on Dec 06, 2003 at 00:39 UTC

    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.";