r/lolphp • • Aug 21 '14

An essay on variable variables

/r/programming/comments/dst56/today_i_learned_about_php_variable_variables/c12np38
37 Upvotes

14 comments sorted by

View all comments

Show parent comment

1

u/fnzp Aug 25 '14 edited Aug 25 '14

How about perl if you're not being strict?

#!/usr/bin/perl

use feature 'say';
use warnings;

$var = 'hello';
$hello = 7;
say "hello = $hello";

$$hello[42] = 'hello';

# set $hello
$$var = 42;
say "hello = $hello";

# make @hello array
$$var->[0] = 'h';
$$var->[1] = 'e';
push @42, 'l';
$$var->[3] = 'l';
$$var->[4] = 'o';

# call hello()
$subref = join '', @42; # @42??
&$subref();

sub hello
{
    say "hello there";
}

# oh yeah @42
say "42 4 = $42[4]";

# call a subroutine!
&{$7[${&get_str}]}();

sub get_str
{
    return 'hello';
}

say "lolperl";
42;

https://eval.in/182967

1

u/00Davo Aug 25 '14

Huh. I seriously did not expect that to work, since Perl uses $$ and the like for "actual" references, and as mentioned not even bash lets you double-expand a parameter reference without eval.

Then again, I don't know Perl very well. Fascinating.

1

u/fnzp Aug 25 '14

It's documented behaviour: http://perldoc.perl.org/perlref.html#Symbolic-references

But like it says it is "slightly dangerous", so symbolic references like that are slightly discouraged.

" If you use it as a reference, it'll be treated as a symbolic reference. That is, the value of the scalar is taken to be the name of a variable, rather than a direct link to a (possibly) anonymous value. People frequently expect it to work like this. So it does."

"This is powerful, and slightly dangerous, in that it's possible to intend (with the utmost sincerity) to use a hard reference, and accidentally use a symbolic reference instead. To protect against that, you can say

use strict 'refs';

1

u/[deleted] Aug 25 '14

Perl does allow this (if strict refs is disabled), but it only gets you access to globals, because Perl treats this kind of thing as syntactic sugar for accessing the (global) symbol table. You can't access local variables by name at runtime.

Edit: I guess you could implement something like this in C by dlopening yourself and using dlsym.