Chrys Ugwu Chrys Ugwu - 1 month ago 12
Perl Question

Perl get parameter datatype

Am trying to make a subroutine that replaces data depending on datatype: the problem is i can't get the datatype of the parameter, i used this:

sub replace {
my ($search, $replacement, $subject) = @_;

if (ref($search) eq "HASH") {
print "r is a reference to a HASH.\n";
}
elsif (ref($search) eq "SCALAR") {
print "r is a reference to a SCALAR.\n";
}
elsif (ref($search) eq "ARRAY") {
print "r is a reference to a ARRAY.\n";
}
}

my $str = "Foo";
my @arr = ("Foo");

replace($str);
replace(@arr);


But none works. am really new to perl

Answer

ref() takes a reference to something, not the something itself. Here:

replace($str);
replace(@arr);

...you are sending in the something directly. Send in a reference to the something instead, by putting a \ in front of it (which says, "take a reference to this something"):

replace(\$str);
replace(\@arr);

Output:

r is a reference to a SCALAR.
r is a reference to a ARRAY.

Note also that in your replace() function, in this line:

my ($search, $replacement, $subject) = @_;

You are effectively asking for a scalar value as the thing to search, so passing in a list (array, hash etc) will clobber $replacement and $subject if the passed in list has more than one element, so you may want to do something like this to ensure you're getting the proper params, and nothing is clobbered unexpectedly:

sub replace {
    my ($search, $replacement, $subject) = @_;
    die "first arg must be a ref\n" if ! ref $search;

Of course, you can do further argument checking, but this'll ensure that the first parameter can only be a reference to something. Instead of die(), you can also just return so the program doesn't crash, or print or warn and then return.

Comments