Re: how to tell object type?
Re: how to tell object type?
Charles Bailey
Fri, 10 May 1996 17:51:26 -0400 (EDT)
- Newsgroups:
- perl.porters-gw
- References:
- <180.831761683@castor.humgen.upenn.edu>
> In perl5.002, how do I tell whether an item in an array is a scalar or an
> array?
>
> I want to have and array containing @a = [a, 1, [b,c]];
>
> Then iterate:
>
> foreach $item (@a) {
> if (is_scalar $item) {
> # Do something scalar with $item.
> }
> elsif (is_array $item) {
> # Do something arrayed with $item.
> $first_sub_item = $item[0];
> }
> }
>
> I couldn't find anything that looked appropriate in perlref.
If the only possibilities are simple scalars and refs to base types,
then you can do this vis C[:
if (ref $item eq 'ARRAY') {
# Do something arrayed with $item.
$first_sub_item = $item[0];
}
# Refs to anything else here
else {
# Do something scalar with $item.
}
There's no simple way, however, to determine the type of a value if
it's been blessed into some package. You could try C, as in
$is_array = (eval {scalar(@$val)}, $@ eq '');
or repeated C][s:
while ($type = ref $val) {
last if $type eq 'SCALAR' or
$type eq 'ARRAY' or
$type eq 'HASH' or
$type eq 'CODE' or
$type eq 'GLOB' or
$type eq 'REF' or
$type eq 'FORMLINE' or
$type eq 'GLOB' or
$type eq 'UNKNOWN';
$val = $$val;
}
Regards,
Charles Bailey bailey@genetics.upenn.edu
Inter alia, C creandum est! :-)
]