Debugging message routine with line directives

This example Perl script shows how to print a message with a line directive in Perl using caller.

#!/home/ben/software/install/bin/perl
use warnings;
use strict;

sub debugmsg
{
    my ($msg) = @_;
    my (undef, $file, $line) = caller (0);
    printf ("%s:%d: ", $file, $line);
    if ($msg) {
        print $msg;
    }
    print "\n";
}

sub othersub
{
    debugmsg ("Here I am.");
}

debugmsg ("Nothing special to say");
othersub ();
debugmsg ();

(download)

The output of this program looks like this:

message-with-line.pl:21: Nothing special to say
message-with-line.pl:18: Here I am.
message-with-line.pl:23: 


Copyright © Ben Bullock 2009-2019. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com) or use the discussion group at Google Groups. / Privacy / Disclaimer