Error in Sect. 7 on using a variable as a variable name

[email protected] (Eric Pement)
Newsgroups perl.perlfaq.workers
Message-ID <[email protected]>
To whom it may concern:

In trying to learn about references, I believe I've found an error in
the Perl FAQ, section 7 ("General Perl Language Issues"), under the
question, "How can I use a variable as a variable name?" The problem
exists in the documentation for Perl 5.6 and Perl 5.8. I tried
emailing this message to "[email protected]" and got
no response. Now that I've got a newer email address, perhaps I can
get a reply.

The FAQ currently reads in part:

   By using symbolic references, you are just using the package's
   symbol-table hash (like %main::) instead of a user-defined hash.
   The solution is to use your own hash or a real reference instead.

       $fred    = 23;
       $varname = "fred";
       $USER_VARS{$varname}++;  # not $$varname++

This solution does not work and does not provide "24" as the FAQ
authors seem to have intended. This can be demonstrated like so:

    #!/usr/bin/perl
    use strict;
    my ($fred, $varname, %USER_VARS);
    $fred    = 23;
    $varname = "fred";
    $USER_VARS{$varname}++;
    print "Value is: $USER_VARS{$varname}\n";

The output is "Value is: 1". So how should this be corrected? Here's
a replacement I suggest for the FAQ. It returns "24", as expected:

    $USER_VARS{fred} = 23;
    $varname         = "fred";
    $USER_VARS{$varname}++;  # not $$varname++

Finally, the FAQ says another solution is to use a real reference
instead. Perhaps you could tell new perl users how this is done:

    $fred       = 23;
    $varname    = \$fred;
    $$varname++; 

Thanks in advance for your time.


-- 
Eric Pement - [email protected]
Education Technical Services, MBI
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.