0

I have the following in a script that runs under mod_perl

Logger::log("\$1 = '$1'");
Logger::log("\$ 1 = '$1'");
Logger::log("\\$1 = '$1'");

Which outputs the following into my log file:

logger:  = ''
logger: $ 1 = ''
logger: \ = ''

$1 is known to be null. Is this a bug in mod_perl2 or is it something else I'm missing?

shiftycow
  • 232
  • 2
  • 11
  • 1
    What output were you hoping to get? – crazyscot Jun 01 '10 at 21:04
  • Is the `Logger::log` method doing interpolation on its input? Where does the `Logger::log` method come from, anyway? – mob Jun 01 '10 at 21:07
  • The output I was hoping to get was "$1 = ''". The logger module is custom and the line that outputs to the log file looks like: print LOG "$date: $msg\n"; So it is doing it's own interpolation of the string later. Could this be what is doing it? – shiftycow Jun 01 '10 at 22:07

2 Answers2

2

Did you try:

Logger::log(q!$1 = '! . $1 . q!'!);

or, to avoid warnings:

Logger::log(q!$1 = '! . ( defined $1 ? $1 : '' ) . q!'!);

The idea here is that q!...! doesn't interpolate its contents, so you know for sure the first part of the string will be $1 = ". If it's still not appearing in the output, then you know Logger::log() or something it calls is interpolating its arguments, which probably shouldn't happen.

Oh, and if you're using a more modern Perl, the second example can use ( $1 // '' ) instead.

DougWebb
  • 680
  • 5
  • 11
1

If you're worried about catching and accidently printing nulls, there's a quick and easy way that almost everyone will recommend you do first: add the following to your program:

use strict;
use warnings;

The problem in particular seems odd; when I do

my $foo = 'zip';
$foo =~ /(bal)/;
print "\$1: '$1'";

I get

$1: ''

(and with use strict and warnings, the additional error

Use of uninitialized value in concatenation (.) or string at - line 5.

Of course, you can prevent $1 from ever being null if you test your regex:

if ($foo =~ /(pattern)/) {
    # $1 is guaranteed to be ok here, if it matched
}

So yeah, it might be your logger re-interpreting $1 as something else. Try adding two more \\; one for escaping the $, and another for escaping an extra backslash. Thus it'd look like

print "\\\$1: '$1'";  
Robert P
  • 15,707
  • 10
  • 68
  • 112
  • Adding the two extra "\\" successfully escapes the $1, but it adds another "\" to the output, so it looks like "Tue Jun 1 16:21:31 MDT 2010: \$1 = ''". Which is still kind of strange to me, but good enough for debugging purposes. – shiftycow Jun 01 '10 at 22:24