CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Advanced:
How to concatenate strings to rename var

 



Jimmy200
New User

Aug 19, 2008, 1:41 AM

Post #1 of 3 (1819 views)
How to concatenate strings to rename var Can't Post

I want to concatenate two strings, one held in a variable, and the other a literal string to form one word, and then rename a variable as that word.

ie:-

$type = 'perl';
$oldvar = 10;
$oldvar = $type + '_context';
print $perl_context;

which would print the value 10. I have been told that this is possible but I cannot find how to do it.

NB. This code does not work.
If there are three possible problems, and you circumvent these, a fourth and previously unseen problem will promptly develop!


shawnhcorey
Enthusiast


Aug 19, 2008, 6:09 AM

Post #2 of 3 (1811 views)
Re: [Jimmy200] How to concatenate strings to rename var [In reply to] Can't Post


In Reply To
I want to concatenate two strings, one held in a variable, and the other a literal string to form one word, and then rename a variable as that word.

ie:-

$type = 'perl';
$oldvar = 10;
$oldvar = $type + '_context';
print $perl_context;

which would print the value 10. I have been told that this is possible but I cannot find how to do it.

NB. This code does not work.


What you want is called a symbolic reference. See `perldoc perlreftut` and `perldoc perlref`. It is strongly recommended not to use them.

But to do so:

Code
no strict; 
$type = 'perl';
$oldvar = 10;
$sym_ref = $type . '_context';
print "\$sym_ref = \"$sym_ref\"\n";
$$sym_ref = $oldvar;
print "\$perl_context = \"$perl_context\"\n";


Instead of using symbolic references, use a hash:

Code
$data_hash{ $type . '_context' } = $oldvar; 
use Data::Dumper;
print '%data_hash : ', Dumper \%data_hash;


__END__

I love Perl; it's the only language where you can bless your thingy.

Perl documentation is available at perldoc.perl.org. The list of standard modules and pragmatics is available in perlmodlib.

Get Markup Help. Please note the markup tag of "code".


KevinR
Veteran


Aug 19, 2008, 11:13 AM

Post #3 of 3 (1796 views)
Re: [shawnhcorey] How to concatenate strings to rename var [In reply to] Can't Post

I agree with shawnhcorey, use a hash. Anytime you want to do something like this a hash is more than likely the way to go. Symbolic references should be avoided.
-------------------------------------------------

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives