Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Perl – Padding a string with whitespace and printing it

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$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.

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading