tags:

views:

187

answers:

4

Hello! 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"
+4  A: 

I don't like option 2 as it introduces an unecessary 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 ;
justintime
+3  A: 

I would prefer:

sprintf "%-7s : %s", $key, $value;

or

sprintf "%-*s : %s", $p, $key, $value;

instead all this weird stuff.

Hynek -Pichi- Vychodil
A: 

I looks a little weird, but it works ( until now ).

#!/usr/bin/env perl
use warnings; use strict;
use 5.010;
use utf8;
use Term::Size;
my $columns = ( Term::Size::chars *STDOUT{IO} )[0];
binmode STDOUT, ':encoding(UTF-8)';
use Text::Wrap;
use Term::ANSIColor;

sub my_print {
    my( $key, $value, $prompt, $color, $p ) = @_;
    my $length = length $key.$prompt;
    $p -= $length; 
    my $suff = ( ' ' x $p ) . $prompt;
    $key .=  $suff;
    $length = length $key;
    my $col = $columns - $length;
    $Text::Wrap::columns = $col;
    my @array = split /\n/, wrap ( '','', $value ) ;
    $array[0] = colored( $key, $color ) . $array[0];
    for my $idx ( 1..$#array ) {
    $array[$idx] = ( ' ' x $length ) . $array[$idx];
    }
    say for @array;
}

my $prompt = ' : ';
my $color = 'magenta';
my $p = 30;
my $key = 'very important text';
my $value = 'text ' x 40;

my_print( $key, $value, $prompt, $color, $p );
sid_com
+1  A: 

Call me old-school, but I'd use printf() or sprintf():

printf "%-33s%s%s\n", $key, $prompt, $value;

That left justifies the string $key into 33 spaces, adds $prompt and $value and a newline. If I wanted to calculate the length for the first part dynamically:

printf "%-*s%s%s\n", $len, $key, $prompt, $value;

Since it is one line instead of the question's 4 (option 1) or 6 (option 2), it scores favourably on the succinctness scale.

Jonathan Leffler
Since I asked a question about best practice it is difficult form me now to not agree with your answer - with printf the code looks nicer, with my_print the output.
sid_com