Jim
Jim

Reputation: 19572

Perl references. How do we know it is one?

I am new to Perl and reading about references.
I can not understand how doe one know if the variable he work on is a reference.
For instance if I understand correctly, this:
$b = $a could be assigning scalars or references. How do we know which is it?
In C or C++ we would know via the function signature (*a or &a of **a). But in Perl there is no signature of parameters.
So how do we know in code what is a reference and what is not? Or if it is a reference to scalar or array or hash or another reference?

Upvotes: 1

Views: 115

Answers (3)

ikegami
ikegami

Reputation: 385917

You're asking the wrong question.

While there is a function called ref and another called reftype, these are not functions you should ever need to use.

It's bad to check the type of variables, because there's no way to effectively know without actually using it as intended due to overloading and magic.

For example, say you designed a function that accepts a reference or a string. That would be a bad design because an object that overloads stringification is both.

A good interface would use context to differentiate the arguments. For example, it could differentiate based on the number of arguments,

foo($point_obj)
   -vs-
foo(x => $x, y => $y)

based on the value of other arguments,

foo(fh => $fh)
   -vs-
foo(str => $file_contents)

or based on the choice of function called

foo_from_fh($fh)
   -vs-
foo($file_contents)

So the answer is: You know it's a reference because your documentation instructs the caller of your function to pass a reference. If you got passed something other than a reference and it's used as a reference, the caller will get a strict error for their error.

Upvotes: 4

Tyler D
Tyler D

Reputation: 594

The ref function is what you're looking for. Documentation is available at http://perldoc.perl.org/functions/ref.html

ref EXPR

Returns a non-empty string if EXPR is a reference, the empty string otherwise. If EXPR is not specified, $_ will be used. The value returned depends on the type of thing the reference is a reference to...

Upvotes: 1

Mat
Mat

Reputation: 206727

Perl has a ref that you can use for that:

Returns a non-empty string if EXPR is a reference, the empty string otherwise. [...]

The string returned (if non-empty) will tell you the type of object the reference references.

Upvotes: 9

Related Questions