The Author Online Book Forums are Moving

The Author Online Book Forums will soon redirect to Manning's liveBook and liveVideo. All book forum content will migrate to liveBook's discussion forum and all video forum content will migrate to liveVideo. Log in to liveBook or liveVideo with your Manning credentials to join the discussion!

Thank you for your engagement in the AoF over the years! We look forward to offering you a more enhanced forum experience.

import-bot (20211) [Avatar] Offline
#1
[Originally posted by cperljim]

Regarding the solutions on page 21 in particular and the other programs in
general, warnings such as "Use of uninitialized value in hash element..."
along with results like "In , 1 CD's were released." can be avoided by using
`defined' to check for undef variables. For instance, take "Solution 1: simple
hash" on page 21 and change
$years{$year}++;
to
$years{$year}++ if (defined $year);

This will silence the aforementioned warning and eliminate the bogus (year
less) result, "In , 1 CD's...".

If you would rather deal with undef variables explicitly, use this instead:

if (defined $year) {
$years{$year}++;
} else {
# deal with undef variable
# e.g., print message to STDERR or to a log file
}

For solution 2, change
push @{$years{$year}}, $rec;
to
push @{$years{$year}}, $rec if (defined $year);

There are probably other programs in your book that should use "if
(defined...)" as well.
import-bot (20211) [Avatar] Offline
#2
Re: Suggestion: use "if (defined...)"
[Originally posted by dave]

> Regarding the solutions on page 21 in particular and the other programs in
> general, warnings such as "Use of uninitialized value in hash element..."
> along with results like "In , 1 CD's were released." can be avoided by using
> `defined' to check for undef variables. For instance, take "Solution 1: simple
> hash" on page 21 and change
> $years{$year}++;
> to
> $years{$year}++ if (defined $year);
>
> This will silence the aforementioned warning and eliminate the bogus (year
> less) result, "In , 1 CD's...".
>
> If you would rather deal with undef variables explicitly, use this instead:
>
> if (defined $year) {
> $years{$year}++;
> } else {
> # deal with undef variable
> # e.g., print message to STDERR or to a log file
> }
>
> For solution 2, change
> push @{$years{$year}}, $rec;
> to
> push @{$years{$year}}, $rec if (defined $year);
>
> There are probably other programs in your book that should use "if
> (defined...)" as well.

You're right that my code assumes that the data will all be in the correct
format and that you'll therefore always get a value for $year.

If you're dealing with potentially "dirty" data (which you'll always find in
the real world), my preference would be to eliminate invalid data as early as
possible.

while (<STDIN>smilie {
chomp;
my $year = (split / /)[3];

warn "Invalid record on line $.", next unless defined $year;

# rest of code
}

hth,

Dave...