in reply to Using undef scalar as arrayref

Weird. I've never noticed this before. There is one problem with your post (unrelated to the for (@$arrayref) working with $arraryref being undef):
If i put this line before the if, then things are ok:
@$arrayref;
But thats not cool, and results in a warning too.
That can't work at all:
#!/usr/bin/perl -w use strict; my $arrayref; @$arrayref; # line 5 print "ok";
Useless use of a variable in void context at test.pl line 5. Can't use an undefined value as an ARRAY reference at test.pl line 5.

Anyway, I suggest using

if ($arrayref) { ... }
if $arrayref can only be false (undef) or a real ref.

update: about the if ($arrayref) test: if, as you say, arrayref should be false or an arrayref, there's no reason to do an defined() and ref() test, because if the $arrayref is true it should be an arrayref, and if it's not, there's nothing you can usefully do, except throw an exception, which is what will happen by default:

#!/usr/bin/perl -w use strict; my $arrayref = 1; for (@$arrayref) { print "ok\n"; }
Can't use string ("1") as an ARRAY ref while "strict refs" in use at t +est.pl line 5.

Replies are listed 'Best First'.
Re^2: Using undef scalar as arrayref
by shemp (Deacon) on Aug 12, 2005 at 20:36 UTC
    Ack, you're right about what you noticed about line 5. I goofed. You're also right about the defined test.

    The only caveat i can think of is that if the $arrayref got set to an empty arrayref, i'd still not want to do the if conditional (in this situation). So i think the final will be:

    if ( $arrayref && @$arrayref ) {
    which will throw an exception if its not an arrayref.

    I use the most powerful debugger available: print!
        Actually the if is separate from the loop. If there are any elements in the arrayref a flag needs to be set for later that is separate from what is happening in the loop. So its something like this:
        if ( $arrayref && @$arrayref ) { # set the flag } ... foreach my $element (@$arrayref) { # do stuff }
        Of course i could set it in the loop, but then its being set multiple times.

        I use the most powerful debugger available: print!