The other day I got request for help finding out why a certain script prints lot of Use of uninitialized value warnings. For the untrained eyes the warnings were really strange.

The original script that generated the warnings is this:

examples/maze.pl



#!/usr/bin/perl -w use strict; use warnings; my @maze= ( #creating an array of arrays [ qw( e swe we ws ) ], [ qw( se new sw ns ) ], [ qw( ns - ns n ) ], [ qw( ne w ne w ) ], ); my %direction = (n=> [-1, 0], s=>[1,0], e=>[0, 1], w=>[0, -1]); my %full = (e=> 'East', n=> 'North', w=> 'West', s=> 'South'); my($curr_x, $curr_y, $x, $y) = (0, 0, 3, 3); my $move; sub disp_location { my($cx, $cy) = @_; print "You may move "; while($maze[$cx][$cy] = ~/([nsew])/g) { print "$full{$1} "; } print "($maze[$cx][$cy])

"; } sub move_to { my($new, $xref, $yref) = @_; $new = substr(lc($new), 0, 1); if ($maze[$$xref][$$yref]!~/$new/) { print "Invalid direction, $new.

"; return; } $$xref += $direction{$new}[0]; $$yref += $direction{$new}[1]; } until ( $curr_x == $x and $curr_y == $y) { disp_location($curr_x, $curr_y); print "Which way? "; $move =<stdin>; chomp $move; exit if ($move = ~/^q/); move_to($move, \$curr_x, \$curr_y); } print "You made it through the maze!

";

It generates tons of this triplet:

Use of uninitialized value $_ in pattern match (m//) at maze.pl line 21. Use of uninitialized value $1 in hash element at maze.pl line 22. Use of uninitialized value within %full in concatenation (.) or string at maze.pl line 22.

That looks really strange, especially that $_ is not even used in this script. At least not intentionally. Can you spot the problem?

Simplified example

examples/maze_extract.pl



use strict; use warnings; sub f { my ($txt) = @_; if ($txt = ~/(\d+)/) { print $1; } } f("abc def"); f("abc 123 def");

This will generate the following 4 warnings:

Use of uninitialized value $_ in pattern match (m//) at maze_extract.pl line 6. Use of uninitialized value $1 in print at b.pl line 7. Use of uninitialized value $_ in pattern match (m//) at maze_extract.pl line 6. Use of uninitialized value $1 in print at b.pl line 7.

Did this make it easier to spot the problem?

B::Deparse

Let's see what does B::Deparse think.