in reply to Defined vs. undefined

I take it you want to run your program depending on whether the hash %hash has been declared.

This is harder to do than you think. If you run with use strict; somewhere in your code then the program will not run unless %hash is defined.

If you run the code without use strict; somewhere in your code then the program will run whether %hash is declared or not. But there lies the next problem: the hash will magically be created the very first time you refer to it. Therefore the mere fact you are trying to access the hash means that it must exist.

So the only problem you can solve is whether the hash contains anything. If the hash is empty then (@keyarr == 1). Otherwise (@keyarr != 1).

Update: as muntfish correctly identified (@keyarr == 0) is the test to use.

Replies are listed 'Best First'.
Re^2: Defined vs. undefined
by muntfish (Chaplain) on Feb 10, 2006 at 11:50 UTC

    To clarify - unlike scalars, arrays and hashes can't be "undefined". They can be empty, which is slightly different.

    monarch, to test for emptiness, you said:

    If the hash is empty then (@keyarr == 1).

    I think you mean 0 not 1:

    my %hash; my @keyarr = keys %hash; print scalar @keyarr;

    prints 0.


    s^^unp(;75N=&9I<V@`ack(u,^;s|\(.+\`|"$`$'\"$&\"\)"|ee;/m.+h/&&print$&