in reply to Distinguishing between an array of objects and an array of strings

ref is true if its operand is a reference so you can test like this:

use warnings; use strict; my $str = 'Str'; my $rStr = \$str; my $rrStr = \$rStr; print "\$rrStr is ref to ref to str\n" if ref $rrStr and ref $$rrStr; print "\$rStr is ref to str\n" if ref $rStr; print "\$str is str\n" if ! ref $str;

Note that each additional $ dereferences by one.


Perl is Huffman encoded by design.
  • Comment on Re: Distinguishing between an array of objects and an array of strings
  • Download Code

Replies are listed 'Best First'.
Re^2: Distinguishing between an array of objects and an array of strings
by tinita (Parson) on Sep 22, 2005 at 10:30 UTC
    ref is true if its operand is a reference
    slightly different: ref returns the type of object ('ARRAY', 'SCALAR', or the classname).
    if the classname was '0' (zero), then ref would not be 'true'.
    ok, nobody would call their classes '0', just thought i should add that to clarify what ref does.
      ok, nobody would call their classes '0', . . .

      There is a good reason for that.

      $ perl -e'package 0' syntax error at -e line 1, near "package 0" Execution of -e aborted due to compilation errors. $
      Namespace names follow the same rules as variable names.

      After Compline,
      Zaxo

        0 is a perfectly valid variable name. $0 is a well known variable - and @0 and %0 are valid as well. 0 is also valid as a package name - but like many other valid package names, you can't use it as an argument to package.

        No they don't. package declarations do, namespaces can be anything.

        *{ anything } = \ anything; bless ..., anything;
        my $pkg = "0"; my $o = bless { }, $pkg; print ref $o;
      Indeed, and unfortunally, if $var isn't a reference, ref($var) returns a false, but defined value, so testing for defined ref($var) is even worse than testing for ref($var). However, it isn't possible to bless something into a package with no name, if the second argument of bless equals the empty string, the thing is blessed into main. So, if ref returns anything but the empty string, its argument is a reference.