'Perl: how to format a string containing a tilde character "~"

I have run into an issue where a perl script we use to parse a text file is omitting lines containing the tilde (~) character, and I can't figure out why.

The sample below illustrates what I mean:

#!/usr/bin/perl
use warnings;

formline "  testing1\n";
formline " ~testing2\n";
formline "  testing3\n";

my $body_text = $^A;
$^A = "";

print $body_text

The output of this example is:

testing1
testing3

The line containing the tilde is dropped entirely from the accumulator. This happens whether there is any text preceding the character or not.

Is there any way to print the line with the tilde treated as a literal part of the string?



Solution 1:[1]

The first argument to formline is the "picture" (template). That picture uses various characters to mean particular things. The ~ means to suppress output if the fields are blank. Since you supply no fields in your call to formline, your fields are blank and output is suppressed.

my @lines = ( '', 'x y z', 'x~y~z' );

foreach $line ( @lines ) { # forms don't use lexicals, so no my on control
    write;
    }

format STDOUT =
~ ID: @*
$line
.

The output doesn't have a line for the blank field because the ~ in the picture told it to suppress output when $line doesn't have anything:

  ID: x y z
  ID: x~y~z

Note that tildes coming from the data are just fine; they are like any other character.

Here's probably something closer to what you meant. Create a picture, @* (variable-width multiline text), and supply it with values to fill it:

while( <DATA> ) {
    local $^A;
    formline '@*', $_;
    print $^A, "\n";
    }

__DATA__
  testing1
 ~testing2
  testing3

The output shows the field with the ~:

  testing1
 ~testing2
  testing3

However, the question is very odd because the way you appear to be doing things seems like you aren't really doing what formats want to do. Perhaps you have some tricky thing where you're trying to take the picture from input data. But if you aren't going to give it any values, what are you really formatting? Consider that you may not actually want formats.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 brian d foy