Search code examples
arraysperlscopestrict

Why isn't this in scope? Why is use strict blocking this?


The language is Perl.

#!/usr/bin/perl

use strict;
[...]
while ( my $res = $async->wait_for_next_response )
{
    [...]
    if ($res->is_success)
    {
        [...]
        my @relAuthorList = ($res->content =~ /<a +rel=\"author\" +href=\".*?\".*?>.*?<\/a>/gi);
        if (@relAuthorList)
        {
            if ($#relAuthorlList != 0) # Line 87
            {
                [...]
            }
            [...]
        }
        my @metaAuthorList = ($res->content =~ /<meta +name=\"author\" +content=\".*?\" *?>/gi);
        if (@metaAuthorList)
        {
            if ($#metaAuthorlList != 0) # Line 105
            {
                [...]
            }
            [...]
        }
        [...]
    }
    [...]
}

When I run it, I get these errors:

$ ./findAuthorCanonical
Global symbol "@relAuthorlList" requires explicit package name at ./findAuthorCanonical line 87.
Global symbol "@metaAuthorlList" requires explicit package name at ./findAuthorCanonical line 105.
Execution of ./findAuthorCanonical aborted due to compilation errors.
$

I'm stumped. Strict is on. I'm using the my keyword to declare the array variables. I'm returning results from the =~ operator as lists into arrays. I'm testing the arrays to make sure they have elements in them before I try to get the last index using the $#array as outlined in perldata.

When I turn strict off, it works as expected.

I've tried predeclaring them as arrays before I put any contents in them:

my @relAuthorList = [];
my @metaAuthorList = [];

That didn't work either.

Most of the answers around this involve scoping errors, but I can't see any I've made here. Some involve forgetting to declare a variable with my but I've done that. I've seen one that involves a type mismatch, trying to treat a scalar as an array. I couldn't find anything relevant to this.

So I ask: What am I doing wrong here?


Solution

  • strict worked here. The declaration of the 2 arrays is spelled differently than their spelling in the lines 87 and 105.

    Also, your checks for the arrays != 0 would allow an empty array (== -1). If you're checking for more than 1 element, the test would be >=1 if I understand your intent here. Maybe you meant @relAuthorList != 0 (which says count of items is 1 or more).