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

Sorry for the post, my mistake was related to something else and I mistakenly took it for perl behavior I wasn't familiar with (don't you hate it when that happens?).

This should be a simple question, but I'm having a hard time finding the answer.

If I have a pointer, say $a->{apple}, and I want to set a variable with the value of what it's pointing to, what is the best way to do this?

Currently, I've been doing this.

my $b = "" . $a->{apple};
But that seems like a weird solution to me, especially if I want to get a numeric value. Is there a better way? Thanks in advance.

-----------------------------------
Washizu
Odd Man In: Guns and Game Theory

Replies are listed 'Best First'.
Re: Getting the value of a pointer
by ikegami (Patriarch) on Jul 18, 2005 at 17:35 UTC

    Your terminlogy is confusing. $a->{apple} has a value; it doesn't point to one.

    my $b = $a->{apple};

    would be equivalent to you snippet, except it won't convert the value to a string.
    If $a->{apple} is a string, it will copy the string.
    If $a->{apple} is a number, it will copy the number.
    If $a->{apple} is a reference, it will copy the reference.
    If $a->{apple} is undefined, $b will be undefined.

    Similarly, I've seen many people do
    my_func("$var1", "$var2", "$var3");
    instead of
    my_func($var1, $var2, $var3);
    for no reason.

    Concatenating with empty strings ("".$var) or quoting variables ("$var") is only needed to force stringification, and stringifying a variable is practically never needed. Functions that require a string (such as print, eval EXPR and the LHS of the regexp match operator) will stringify variables as needed, automatically.

      Agreed.

      Digression: One place where you may see explicit stringification is when using Class::DBI, where stringification produces a (numerical) primary key.

      # untested my $object = Foo->retrieve(1234); # an object &function_needing_int_not_object('' . $object);

        That's odd. It should overload numerification and numerical ops instead of (or in additon to) stringification.

        There is only one case where stringification is needed that comes to mind: When the function behaves differently whether a parameter is a string* or an object, and the parameter is an object with an overloaded stringification operator. For example,

        sub output { my ($fh, ...) = @_ if (!ref($fh) && ref($fh) ne 'GLOB') { open($fh, '>>', $fh); } ... }

        * or number vs object, or boolean vs object