perlprinting

How can I pad part of a string with spaces, in Perl?


Which version would you prefer?

#!/usr/bin/env perl
use warnings; 
use strict;
use 5.010;

my $p = 7; # 33
my $prompt = ' : ';
my $key = 'very important text';
my $value = 'Hello, World!';

my $length = length $key . $prompt;
$p -= $length; 

Option 1:

$key = $key . ' ' x $p . $prompt;

Option 2:

if ( $p > 0 ) { 
    $key = $key . ' ' x $p . $prompt;
}
else {
    $key = $key . $prompt;
}

say "$key$value"

Solution

  • I don't like option 2 as it introduces an unnecessary special case.

    I would refactor out the construction of the prompt suffix:

        # Possible at top of program
        my $suffix =  ( ' ' x $p ) . $prompt;
    
        # Later...
    
        $key .= $suffix ;