Skip to Main Content
Perl Cookbook
book

Perl Cookbook

by Tom Christiansen, Nathan Torkington
August 1998
Intermediate to advanced content levelIntermediate to advanced
800 pages
39h 20m
English
O'Reilly Media, Inc.
Content preview from Perl Cookbook

Making Perl Report Filenames in Errors

Problem

Your program works with files, but Perl’s errors and warnings only report the last used filehandle, not the name of the file.

Solution

Use the filename as the filehandle:

open($path, "< $path")
    or die "Couldn't open $path for reading : $!\n";

Discussion

Ordinarily, error messages say:

               
                  Argument "3\n" isn't numeric in multiply at tallyweb line 16, <LOG> chunk 17.

The filehandle LOG doesn’t help much because you don’t know which file the handle was connected to. By using the filename itself as indirect filehandle, Perl produces more informative errors and warnings:

               
                  Argument "3\n" isn't numeric in multiply at tallyweb
               
                      line 16, </usr/local/data/mylog3.dat> chunk 17.

Unfortunately, this doesn’t work with strict refs turned on because the variable $path doesn’t really have a filehandle in it, but just a string that sometimes behaves as one. The chunk mentioned in warnings and error messages is the current value of the $. variable.

See Also

Section 7.1; the open function in perlfunc(1) and Chapter 3 of Programming Perl

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 in a Nutshell

Perl in a Nutshell

Nathan Patwardhan, Ellen Siever, Stephen Spainhour
Perl Best Practices

Perl Best Practices

Damian Conway
Mastering Perl

Mastering Perl

brian d foy
Perl Cookbook, 2nd Edition

Perl Cookbook, 2nd Edition

Tom Christiansen, Nathan Torkington

Publisher Resources

ISBN: 1565922433Supplemental ContentCatalog PageErrata