perl

What does this line with "!%" mean in Perl?


I'm looking at some code, but I don't understand what the following line is doing/checking:

return if !%Foo::Details:: ;

What exactly is this doing? Is it checking for the existence of module Foo::Details?


Solution

  • A hash in scalar context returns false if it's empty, so your code returns an empty list if the hash %Foo::Details:: is empty.

    That hash is the symbol table for the Foo::Details namespace. If a package variable or sub is created in the Foo::Details namespace, a glob corresponding to the name of the variable or sub will be created in %Foo::Details::. So, it returns an empty list if the Foo::Details namespace is empty.

    $ cat >Foo/Details.pm
    package Foo::Details;
    sub boo { }
    1;
    
    $ perl -E'say %Foo::Details:: ?1:0;'
    0
    
    $ perl -E'use Foo::Details; say %Foo::Details:: ?1:0;'
    1
    

    It might be trying to check if the Foo::Details module has been loaded, but it's not perfect. For example, it will think Foo::Details has been loaded even if only Foo::Details::Bar has been loaded. To check if Foo::Details has been loaded, it might be better to check if $INC{"Foo/Details.pm"} is true. The problem with that approach is that it won't find "inlined modules".