Re: What type are you? Mr Hash, Sir Array, or Miss Scalar?
by hv (Prior) on May 12, 2004 at 14:27 UTC
|
The Scalar::Util module has a function 'reftype':
reftype EXPR
If EXPR evaluates to a reference the type of the variable referenced is returned. Otherwise "undef" is returned.
$type = reftype "string"; # undef
$type = reftype \$var; # SCALAR
$type = reftype []; # ARRAY
$obj = bless {}, "Foo";
$type = reftype $obj; # HASH
Hugo
| [reply] [d/l] |
|
|
| [reply] [d/l] |
|
|
Ahhh, thanx, or else i will looked so DUMB :)
Yes, i mean programatically, not me identifying variables (i know that, already).
This is important when we using reference, since i need to know what the reference is pointing to...
| [reply] |
|
|
| [reply] |
|
|
I've tried it out, but why is this doesn't work?
I've used ref instead, but never on advanced level (on class etc.
| [reply] |
Re: What type are you? Mr Hash, Sir Array, or Miss Scalar?
by Limbic~Region (Chancellor) on May 12, 2004 at 14:28 UTC
|
Doraemon,
There is a way to tell a variable's type by using defined() bla,bla,bla? That is news to me.
I am going to assume you mean some variable seen by your program that comes externally. If it was your own code you would only need to look at the sigil ( % => hash, $ => scalar, @ => array). If that is the case then you could probably get away with using ref (see perldoc -f ref). There are certainly limitations in ref, but I think it will fit your immediate needs.
Cheers - L~R | [reply] |
|
|
defined() bla,bla,bla? yeah, right!
Just a silly joke. Never seriously thought about that (harhar)
But i've tried the ref, and it works just fine...problem solved
| [reply] |
|
|
my %test = ('test1'=>'value',
'test2'=>'value');
my $hash_ref = \%test;
print "hash ref" if($hash_ref =~ m{HASH});
I used that once(before I knew about ref). I don't know if that's horribly bad practice or not, but it works. So basically you could go to the trouble (again I don't know why you would want to) of setting up your own ref via a case statement of regex's
| [reply] [d/l] |
Re: What type are you? Mr Hash, Sir Array, or Miss Scalar?
by haoess (Curate) on May 12, 2004 at 14:26 UTC
|
I don't see any problem. A variable containing an array is named @array, a hash variable is named %hash, and a scalar variable is, you guess it, $scalar.
You should tell us what you want to do more exactly.
-- Frank
| [reply] |
|
|
Say that, to someone who don't know what Perl is :)
Just kidding. What i meant,
# type = what_type($ref);
| [reply] [d/l] |