Joel G Mathew
Joel G Mathew

Reputation: 8061

Proper way to string interpolate an array element within printf

While working on Schwartz's Learning Perl, I came across an exercise where I am supposed to accept a number of user input strings, where the first input is to be the width determining right justified output for the other strings.

In other words, inputs:

10
apple
boy

Output should be:

       10
    apple
      boy

where output is right justified by 10.

I tried using arrays to approach the problem:

#!/usr/bin/perl
use strict;
use warnings;
my @array;
while (<>) {
    chomp($_);
    push @array, $_ ;
}

while (@array) {
    printf ("%$array[0]s \n", shift @array);
}

But after formatting and printing '10' correctly, I get errors:

$ perl test.pl 
10
apple
boy
        10 
Invalid conversion in printf: "%a" at test.pl line 11, <> line 3.
%apples 
Argument "boy" isn't numeric in printf at test.pl line 11, <> line 3.
0oys 

I tried a variety of methods to force interpolation of the array element by enclosing it in braces, but all these have resulted in errors. What's the proper way to string interpolate array elements within printf (if that's the right term)?

Upvotes: 1

Views: 621

Answers (1)

Zaid
Zaid

Reputation: 37146

Here's a more Perlish way to write it that avoids having to perform an explicit shift. It's a lot more do-what-I-mean since the format control variable is not part of @array from the start:

use strict;
use warnings;

my ( $length, @array ) = <>;
chomp( $length, @array );

printf "%${length}s\n", $_ for ( $length, @array );

Upvotes: 2

Related Questions