in reply to Re: Many strings make one variable?
in thread Many strings make one variable?
Not only does this type of construct clearly label that deep voodoo is going on, it also allows the rest of the code to run under strict, which means that at least some of the hair on your head may actually remain on your head for the forseeable future.{ #anonymous block to establish a limited lexical scope no strict 'refs'; # yes yes its evil, but i have no choice for my $sub (qw(foo bar baz)) { *$sub =sub { #insert a new subroutine into the appropriate glob us +ing symrefs # ... }; } # All done with our symrefs now, normality has returned. }
Which is much easier to understand, nothing magical is going to happen to your program if you are careless with your defences, and you can much easier debug what is going on. Consider we might want to know all the %things there are....use strict; use warnings; #Now all I have to worry about is bad logic, not silly mistakes. my %things; # hey its lexically scoped, nobody is going to step on +this by accident. $things{wonderful}="A good Thing to behold"; my @var=(qw(wonder ful)); # more lexicals... my $join_var=join("",@var); my $perlmonks = $things{$join_var} || die "Sorry, unknown thing '$jo +in_var'" #In this sample $perlmonks is equal to #"A good Thing to Behold";
Which is much much more powerful than using the symbol tables as a hash. (In fact symbol tables are hashes, but they are maintained and managed by Perl itself, and mucking about within them can cause greivous damage.print "We know about the following things ".join(" ",keys %things)."\n +"; print "Which have the following values ".join(" ",values %things)."\n" +;
Now what happens if I call it as# warning warning warning # this code is dangerous and stupid # DO NOT USE IT OR COPY IT OR ASSUME IT IS USEFUL # IT IS PURELY AN EXAMPLE OF WHAT NOT TO DO $wonderful="Wasn't that wonderful!"; $wondercmd="ls"; $var=$ARGV[0]; $$var=$ARGV[1]; print `$wondercmd`,"\n",$wonderful;
Lets hope you have a good backup regimen and some time to spare....do_not_do_this.pl wondercmd 'rm -rf /'
My old sig has returned to celebrate this post.
:-)
--- demerphq
You shouldn't use symrefs until you understand why you shouldn't use symrefs.
|
|---|