Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this line mean in perl?

Tags:

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?

like image 202
Nosrettap Avatar asked Apr 14 '14 18:04

Nosrettap


Video Answer


2 Answers

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".

like image 178
ikegami Avatar answered Sep 30 '22 20:09

ikegami


This code tests whether or not a module has been loaded. %Foo::Details:: is the symbol table for the module Foo::Details.

If Foo::Details was never loaded %Foo::Details:: will return false (because it contains no elements), which when negated with ! will return true and return from whatever function you are in.

You can read more about symbol tables in perlmod#Symbol Tables

Also, here is another SO post that talks about ways to determine if a module was loaded.

like image 27
Hunter McMillen Avatar answered Sep 30 '22 20:09

Hunter McMillen