Search code examples
perlsubroutine

check the type of variable passed in a subroutine in perl


I want to get the type of variable passed to the subroutine.While googling I came across the under-below solution, but this is not giving satisfactory results . My problem is illustrated in the below example

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

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

    }

Solution

  • ref never produces "STRING". (Well, unless you create a STRING class and bless an object into it.) A normal string is not a reference, so 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";
      }
    }