in reply to Variable Names and References
You can use symbolic references if you switch off "strict refs":
update: you can only refer to GLOBALs with symbolic references. (update2: here's the relevant documentation in perlref) That's why that code still won't work. Here's a working version:for (1..3) { no strict 'refs'; my $ref = \${'str'.$_}; # this creates a hard reference VIA a symb +olic reference # or: my $ref = "str$_"; # this is a purely symbolic reference, +access is the same as above print "The string is $$ref"; }
#!/usr/bin/perl -l use warnings; use strict; our $str1 = qq[A-M o'Foo']; our $str2 = qq[.,rtyu_'']; our $str3 = qq[$<%^]; our $str4 = qq[this works]; my $ref4 = \$str4; print $$ref4; # works as expected for (1..3) { no strict 'refs'; my $ref = \${'str'.$_}; print "The string is $$ref"; }
Note that in your example using a simple array would be much easier, less error-prone and more efficient. Symbolic references are almost only useful these days for creating subroutines / packages at runtime (basically, wherever the only alternative is to use eval STRING).
updated again, added some comments
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Variable Names and References
by chakram88 (Pilgrim) on Mar 09, 2007 at 16:13 UTC | |
|
Re^2: Variable Names and References
by rvosa (Curate) on Mar 12, 2007 at 00:52 UTC | |
by Joost (Canon) on Mar 12, 2007 at 10:25 UTC |