vatheck has asked for the wisdom of the Perl Monks concerning the following question:

{ while (my ($location, $devices) = each %devicecount) { foreach my $line (@workingdata) { my @Fld = split /,/, $line; if (/${location}TEXT/) { $somevar += $Fld[11]; $someothervar += $Fld[12] } } printf OUTPUT "some stuff from the info we gathered"; } }
Every time I run this script with warnings on I get a warning that the variable $location is undeclared once for each line in the @workingdata array and I don't understand why. It appears to use "0" in the pattern match because it never matches any line which it would if it used "".

I have tried taking the my out of the each statement and declaring both $location and $devices as global variables and the script runs with the same warning only once instead of once for each entry in the array and the script hangs eating the same amount of processor and ram but never generates any output to the file. Any help is greatly appreciated.

Replies are listed 'Best First'.
Re: uninitialized variable warning
by jwkrahn (Abbot) on Apr 30, 2008 at 02:47 UTC
    • You are not using $devices anywhere inside the loop so why not use:
      for my $location ( keys %devicecount ) {
    • You are matching /${location}TEXT/ against the contents of $_ but you don't appear to put any data into $_ in your code.
      I do use $devices in the output portion of the script, thats why I am using each instead of keys. I've changed it to declare $location and $devices right inside the begining of the naked block so that its within its scope when I call it during the output portion.

      I finally get it. for some reason I was thinking that $location was outside of its scope for some reason I didn't understand, I feel like a dunce now that I realize it was $_ that was the uninitialized value. I have fixed that as well now.

      Everything is running now and generating the output I was looking for, thanks.
Re: uninitialized variable warning
by oko1 (Deacon) on Apr 30, 2008 at 03:13 UTC

    Try printing the value of '$location' within your loop, and surround it with some sort of visual delimiters. E.g.

    while (my ($location, $devices) = each %devicecount) { # Test the above variables print "Loc: [[[$location]]]\tDev: [[[$devices]]]\n"; foreach my $line (@workingdata) { ...

    It doesn't seem likely that it's actually undefined, since you can't have an undefined key in a hash. If you show us more of your code - especially a complete but minimal script that can be executed and demonstrates the error - we'd be in a much better position to help you.

    Update: You should also make sure that the value of '$location' within the regex is treated as a literal string; this will prevent problems if it happens to contain any regex metacharacters. I.e.,

    if (/\Q$location\ETEXT/) {
    
    -- 
    Human history becomes more and more a race between education and catastrophe. -- HG Wells