Home > Mobile >  Perl - Padding a string with whitespace and printing it
Perl - Padding a string with whitespace and printing it

Time:08-06

I have a string "A" and a string "B".

I want to add a certain amount of whitespace between A and B, then print it. I want the resulting print to be "A (lots of spaces here) B".

My idea is to pad "A" with whitespace to the right. I tried to accomplish this by:

$A .= (" " x 10)

then concatenate A and B, and print it.

However, this resulting print is "A \ \ \ \ \ \ \ \ \ \ B"

How do I get whitespace instead of these backslashes in my print? I'm not sure what I'm missing.

CodePudding user response:

The code you posted does not produce the output you describe.

$ perl -Mv5.14 -e'
   my $A = "A";
   my $B = "B";
   $A .= " " x 10;
   say $A . $B;
'
A          B

If you know the amount of space you need, generating it using " " x 10 is quite appropriate.

$ perl -Mv5.14 -e'say "A", " " x 10, "B";'
A          B

If instead, you know the size of the column, you could use printf.

$ perl -Mv5.14 -e'say sprintf "%-10s %s", "A", "B";'
A          B

And there's also forms.

$ perl -Mv5.14 -e'
  use Perl6::Form qw( form );
  print form "{<<<<<<<<} {<<<<<<<<}", "A", "B";
'
A          B
  • Related