perlpal has asked for the wisdom of the Perl Monks concerning the following question:

Hi, Please could i know the difference between hard references and symbolic references? I have a basic understanding of hard references, but the symbolic ones are a bit confusing. Thanks in Advance!
  • Comment on Hard reference vs Soft/Symbolic reference

Replies are listed 'Best First'.
Re: Hard reference vs Soft/Symbolic reference
by tilly (Archbishop) on Jan 21, 2009 at 05:35 UTC
    MJD gives a great explanation of symbolic references and why they are bad at http://perl.plover.com/varvarname.html. Be sure to read all 3 parts of the article.

    Update: I should summarize this topic. If $foo has the string "bar", then $$foo refers to $bar. The problem comes when you think that $foo has the string "bar" when it has some other string instead, causing potentially nasty side-effects. If you use strict.pm, it will disable this functionality (you can re-enable it locally with no strict 'refs';). In general you don't want to use symbolic references because it is almost as easy to use hashes instead, and they avoid the major potential pitfalls. (There are a small number of things that are very hard to do without symbolic references. Most programmers will never need to do them.)

    Hard references are a entirely different kind of beast. Hard references are effectively pointers to the variable in question. So the line $foo = \$bar; means that $$foo is now $bar. There are things you can do with hard references that would be next to impossible otherwise (for instance references underlie Perl's OO system), and they are much, much safer. If you want an overview of the syntax of hard references, read references quick reference.

Re: Hard reference vs Soft/Symbolic reference
by kennethk (Abbot) on Jan 21, 2009 at 05:38 UTC

    The general reference for all references, including symbolic ones is perlref and a basic intro can be found in perlreftut. You should likely read through both.

    Under most circumstances, you should avoid symbolic references since they make debugging more difficult, security can be comprimised and nearly everything you can do with them can be done with ordinary, "hard" references. There are exceptions (e.g. manipulating the symbol table), and those are discussed in the relevant section of perlref. The basic concept behind them is rather than storing the memory address of the variable of interest, as is done with normal references, you store in your variable the name of a variable of interest. This is then dereferenced using the same syntax. So, for example you could do the following:

    my $string = 'Hello World!'; my $var_name = 'string'; print ${$var_name};

    The scalar dereference looks through the lexical space to see if it can find a scalar variable named 'string', and then when it does, performs the substitution.