in reply to Re^3: How to check if an array element reference exists or not
in thread How to check if an array element reference exists or not

Thanks for the reply. Maybe these screen shots of the debugger will explain my question. With if ( defined $row[7] ) and if ( $row[7] ), neither returns true in the case of the second screen shot.

Replies are listed 'Best First'.
Re^5: How to check if an array element reference exists or not
by almut (Canon) on Apr 14, 2010 at 09:26 UTC

    You can use ref to figure out the type of a reference/object. In your case, it seems you don't want to print it if it's "SCALAR"; or maybe the other way round, you do want to print it if it's "HTML::ElementTable::DataElement".

    if ( ref($row->[7]) eq "HTML::ElementTable::DataElement" ) { print $row->[7]->as_text; }

    Update: a more generic way would be to use can() to directly test whether the method in question is available:

    use Scalar::Util 'blessed'; if ( blessed($row->[7]) and $row->[7]->can("as_text") ) { print $row->[7]->as_text; }

    can() can only be called on blessed references, though, so you'd need to use Scalar::Util... (unless you resort to ugly stuff like if ("$ref"=~/=/ and ...) ).

      Thanks. That did it!
Re^5: How to check if an array element reference exists or not
by Corion (Patriarch) on Apr 14, 2010 at 09:23 UTC

    The point of using Data::Dumper is to get a textual representation of a data structure, so there is then no need to resort to screenshots of a debugger showing a scrolled window of a data structure.

    Your debugger is misleading you. You are either not using strict, or you have two variables declared, @row and $row. They are different.

    You seem to be wanting to check whether the 8th element in the array referenced by $row is defined, but you check whether the 8th element in the array @row is defined.

    Again, use Data::Dumper to look at the data structure you're testing instead of relying on visual inspection combined with guesswork as to what data structure your code really is looking at.

    if (defined $row->[7]) { ...

    should work, according to my interpretation of the dump you show in the offsite link to a screenshot showing your debugger showing a data structure and some code.

      Thanks again for the reply.

      I'm not using strict as I'm just writing a function to complement code that somebody else has written.

      I ran the dumper on $rowand it spit out a 3200KB text file.

      So instead, I ran the Dumper on print Dumper ($row->[7]); and got $VAR1 = \undef;.

      Running if (defined ($row->[7]) ) when $row->[7] is \undef; returns true. I'm guessing that the reference is causing this?
        I'm guessing that the reference is causing this?

        What is this guessing?

        $ perl -le"print \undef" SCALAR(0x3d5790) $ perl -le"print defined \undef" 1 $ perl -le"print \1" SCALAR(0x3d8284) $ perl -le"print defined \1" 1