Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I have a very large amount of files I am processing. Unfortunately, each file is unique although it follows a very specific pattern. I've written a code generator to create file specific parsing subroutines. It's all nearly working except that I can't print out a regular expression with the print command. The expression is being evaluated and the output code is screwed up. How can I avoid this?
print "$line =~ s/^\s+|#//; #trim leading spaces and comment hash\n"; print "$line =~ s/\s+$|\///; #trim trailing spaces and forward slash\n +";
The output becomes
$line =~ s/^s+|#//; #trim leading spaces and comment hash $line =~ s/s+0///; #trim trailing spaces and forward slash
Any insight will be helpful. I've tried breaking it up into pieces and concatenating but that causes errors.

Replies are listed 'Best First'.
Re: Code generation. Printing out regular expressions
by roboticus (Chancellor) on Jan 14, 2010 at 22:16 UTC

    Use single quotes in your print statement:

    print '$line =~ s/^\s+|#//; #trim leading spaces and comment hash',"\n +"; print '$line =~ s/\s+$|\///; #trim trailing spaces and forward slash', +"\n";

    You can use say to avoid the "\n" at the end...

    ...roboticus

      Thanks! That's perfect.
Re: Code generation. Printing out regular expressions
by johngg (Canon) on Jan 14, 2010 at 22:57 UTC

    In addition to roboticus's comments, I'm a little surprised that you get the literal $line in your output. The $line inside the double quotes of each print statement should have interpolated just as the $| did in the second line. Unless, of course, you did something like $line = '$line'; in your code somewhere.

    Your comments detailing what the lines do are inaccurate, for instance, /^\s+|#/ will match one or more spaces anchored to the beginning of the string or a hash anywhere. Is that what you meant? I expect you know this but note that if you are trying to match literal dollar and pipe symbols, they are regular expression metacharacters and should be escaped. Also, if you are trying to match a forward slash it can be more readable to choose a different regex delimiter. Putting all this together:

    print '$line =~ s{^\s+#}{}; #trim leading spaces and comment hash', "\ +n"; print '$line =~ s{\s+/$}{}; #trim trailing spaces and forward slash', +"\n";

    I hope I have guessed your intention correctly and that this is helpful.

    Cheers,

    JohnGG