Skip to Content
Perl Hacks
book

Perl Hacks

by Chromatic, Damian Conway, Curtis Ovid Poe, Curtis (Ovid) Poe
May 2006
Beginner
298 pages
6h 51m
English
O'Reilly Media, Inc.
Content preview from Perl Hacks

Hack #52. Make Invisible Characters Apparent

See what your variables really contain.

Perl has a handful of good debugging techniques. For example, you can fire up the debugger [Hack #59] or write test cases [Hack #53]. If you're just experimenting, or need a quick-and-dirty answer right now, sometimes the easiest technique is to add a few print( ) statements here and there.

This has its drawbacks, though, especially when the printed output looks correct but obviously isn't. Before you flip through the debugger documentation and rejig your debugging statements into test cases, consider a few tricks to make the invisible differences that your computer sees visible to you too. (Then make your test cases, use the debugger, and smarten your comments.)

Bracket Your Variables

A very common mistake is to forget to chomp( ) data read from external sources. Suppose that you're processing a list of files read from another file:

while (<$file_list>)
{
    warn "Processing $_";
    next unless -e $_;
    process_file( $_ );
}

All of the files look correct in the warn( ) output, but the process_file( ) code never occurs.

Tip

warn( ) is better than print( ) because it goes to STDERR by default, which makes it redirectable separately.

Change the debugging line to make the filename more visible:

while (<$file_list>)
{
    warn "Processing '$_'";
    next unless -e $_;
    process_file( $_ );
}

Adding single quotes (or any other visible character) around the filename will likely reveal that all of the filenames within the loop ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Perl Debugged

Perl Debugged

Peter Scott, Ed Wright
Perl 6 Deep Dive

Perl 6 Deep Dive

Andrew Shitov
Learning Perl 6

Learning Perl 6

brian d foy
Perl by Example

Perl by Example

Ellie Quigley

Publisher Resources

ISBN: 0596526741Supplemental ContentErrata Page