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

I tried both those cases, but they always return false and the print statement never gets executed, even when such a cell exists.
  • Comment on Re^2: How to check if an array element reference exists or not

Replies are listed 'Best First'.
Re^3: How to check if an array element reference exists or not
by Corion (Patriarch) on Apr 14, 2010 at 08:57 UTC

    So, how do you determine that "such a cell exists"? I recommend printing your data structure:

    use Data::Dumper; print Dumper $row;

    That will show you whether such a cell exists in $row. Maybe it's the 7th cell, which would be at $row->[6]. Usually, when Perl says that defined $row->[7] is false, Perl is right.

      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.

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

        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.