perl

How to check if $j->{component} is empty in perl?


This doesn't seem to work for me, and can't figure out how to make it work. The system that takes the json I'm creating with this doesn't like "components": null,

if ($s->{category} == ""){
    $j->{components} = "Unspecified";
  }
   else
  {
    j->{components} = $s->{category};
  }

Thanks


Solution

  • Assigning empty string is still assigning something. If you want to know if a hash array does not have a specified key, you can use defined() function. And if you want to destroy an assignment - use undef

    #!/usr/bin/perl
    my $j = {};
    
    $j->{var1} = 1;
    print $j->{var1}, "\n";
    
    print "has var1\n" if (defined($j->{var1}));
    print "does not have var2\n" if (! defined($j->{var2}));
    
    undef $j->{var1};
    print "does not have var1\n" if (! defined($j->{var1}));