[Israel.pm] Detecting Scalar type?

Mikhael Goikhman migo at homemail.com
Fri Jul 25 05:38:49 PDT 2008


On 25 Jul 2008 15:13:37 +0300, Shmuel Fomberg wrote:
> 
> I'm writing an method, that suppose to get a scalar as parameter.
> However, this scalar can be one of few things: file handle, socket, 
> string and so. I need to detect what this scalar is, and act accordingly.
> Does anyone have a piece of code that does that?

my @things = (
	'string',
	\'stringref',
	\*STDOUT,
	[ 'arr', 'ay' ],
	{ ha => 'sh' },
#	IO::Socket->new,  # uncomment after "use IO::Socket;"
	sub { 'anonymous function' },
	undef,
);

for my $thing (@things) {
	my $type = ref($thing);
	# do something accourding to $type, for example, just print it
	print defined $thing ? "$thing is of type '$type'\n" : "undef\n";
}

Regards,
Mikhaer.

-- 
perl -e 'print+chr(64+hex)for+split//,d9b815c07f9b8d1e'



More information about the Perl mailing list