Check the type of a variable passed in a subroutine to perl

I want to get the type of a variable passed to a subroutine. While googling I stumbled upon the below solution but it does not give satisfactory results. My problem is illustrated in the example below.

    sample("test");
    sample(\%a);

    sub sample {
      my ($argv1) = @_;
      if(ref($argv1) eq "STRING") {
        print "string\n";
      }
      elsif(ref($argv1) eq "HASH") {
        print "HASH\n";
      }

    }

      

+3


source to share


2 answers


ref

never creates "STRING". (Well, unless you create a class STRING

and bless an object in it.) A normal string is not a reference, so it ref

returns a false value:



sample("test");
sample(\%a);

sub sample {
  my ($argv1) = @_;
  if(not ref($argv1)) {
    print "string\n";
  }
  elsif(ref($argv1) eq "HASH") {
    print "HASH\n";
  }
}

      

+8


source


So then not Google. Read the official documentation.



ref returns an empty string for scalars.

+2


source







All Articles