Despite what you might be thinking, I'm not talking about printing to a filehandle. However, whileI was trying to help a coworker understand variable interpolation in strings, I came up with the following code:
#!/usr/bin/perl use strict; use warnings; use Test::More tests => 6; my %french_for = ( one => 'un', ); my $num = 'one'; is "$french_for{one}", 'un', 'bare literal key'; is "$french_for{'one'}", 'un', 'single quoted literal key'; is qq[$french_for{"one"}], 'un', 'double quoted literal key'; is "$french_for{$num}", 'un', 'bare variable key'; is "$french_for{'$num'}", 'un', 'single quoted variable key'; is qq[$french_for{"$num"}], 'un', 'double quoted variable key';
The "$french_for{'$num'}" doesn't work because, as hv explained on P5P:
A variable access is parsed as code. "'$num'", the variable being accessed is $num; in "$french_for{'$num'}", the access is to: $french_for{'$num'} which is a nonexistent hash element. I'm not sure what behaviour you were expecting instead, but I've never noticed anyone stumble on this before.
Note that this is precisely what allows you to use tricks like "@{[ 2 + 2 ]}" or "${\( 2 + 2 )}" to interpolate code in a string.
And this allowed me to come up with this:
temp $ touch foo.bar temp $ ls foo.bar temp $ perl -Te '%ENV = (); print "$ENV{`rm foo.bar`}"' temp $ ls temp $
Note that "foo.bar" is now gone. Frankly, I think you'd have to jump through a few hoops to create a security hole here, but I thought it was interesting.
Cheers,
Ovid
New address of my CGI Course.
Formating fixed by Me
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: How to delete a file with a print statement
by ikegami (Patriarch) on Jul 31, 2006 at 16:44 UTC | |
Re: How to delete a file with a print statement
by Anonymous Monk on Aug 04, 2006 at 07:11 UTC |