in reply to Truthfulness of references

return_ref, as its name announces, returns a reference to a hash. That reference gets assigned to a scalar variable ($ref) as is fine an proper. A rather bogus test for "truth" is then made to see if $_ is a reference to anything (is that what you thought the test actually was?).

I'm not sure what issue you are trying to illustrate, however the following code may provide a little illumination:

use strict; use warnings; my $scalar = 'a string is a scalar'; print ref ({}), "\n"; print ref ([]), "\n"; print ref (ret_hash ()), "\n"; print ref (ret_array ()), "\n"; print ">", ref ($scalar), "<\n"; print ref (\$scalar), "\n"; sub ret_hash {my %hash; return \%hash;} sub ret_array {my @array; return \@array;}

Prints:

HASH ARRAY HASH ARRAY >< SCALAR

ref tells you something about the type of reference you point it at (but nothing about scalars). ref on it's own tells you about whatever reference $_ contains (which is the test you were making in your if).


DWIM is Perl's answer to Gödel

Replies are listed 'Best First'.
Re^2: Truthfulness of references
by njcodewarrior (Pilgrim) on Mar 13, 2007 at 11:08 UTC

    Thanks GrandFather. That's what I thought the test was actually doing

    So what's a good way to test for truth here?
    The reason for the post is that I've written a few subroutines that either return a reference to a complex data structure OR filter entries out of the previously created data structure. The problem I noticed was that if I ended up filtering out all of the entries and returning a reference to the filtered data structure, my test for truth returned unexpected results ( ie: it returned true eventhough the data structure was empty.

    3 follow up questions:
    1. Should I be returning references from these types of sub-routines?
    2. If so, what's the best way to return them?
    3. What's a good way to test for truthfulness:

    if ( %$ref ) { ...do something }

    or...

    if ( %$ref && ref $ref eq 'HASH' ) { ...do something }

    Thanks again for your help.
    njcodewarrior

      You wrote:

      3. What's a good way to test for truthfulness:

      "Truthfulness" is an unusual term for the boolean value of something. "Truth value" is more common.

      if ( %$ref ) { ...do something }
      That code is fine if you know that $ref holds a hash ref and you need to decide whether the hash is empty.

      or...

      if ( %$ref && ref $ref eq 'HASH' ) { ...do something }
      Here, it seems, you want to check whether the reference you have is indeed a hash ref, but put this way the condition is pretty much useless. Since you try a hash dereference first, if the ref isn't a hash ref your code will die before it gets to the test.

      You'd have to swap the parts for them to make sense:

      if ( ref $ref eq 'HASH' && %$ref ) {
      Anno