user1610717
user1610717

Reputation: 325

Perl appending (s)printf output to string

I'm parsing some data and organizing it, and now I need to capture it inside a variable.

I've never used printf or sprintf before this.

I'm using printf in a manner like this to organize the data:

printf("%-30s %18s %18s\n", "$a", "$b", "$c\n");

Now I have a variable that's storing a string, and I want to append the organized data to the variable $result.

I tried something like

$result.printf("%-30s %18s %18s\n", "$a", "$b", "$c\n");

and it doesn't work. I tried sprintf too.

Any ideas?

Thanks, S

Upvotes: 7

Views: 10667

Answers (2)

ikegami
ikegami

Reputation: 386501

printf outputs the constructed string to the specified handle (or the current default if omitted) and returns a boolean which indicates whether an IO error occurred or not. Not useful. sprintf returns the constructed string, so you want this.

To concatenate two strings (append one to another), one uses the . operator (or join)

$result . sprintf(...)

But you said this doesn't work. Presumably, it's because you also want to store the produced string in $result, which you can do using

$result = $result . sprintf(...);

or the shorter

$result .= sprintf(...);

Upvotes: 12

TLP
TLP

Reputation: 67910

Don't know what you mean by "tried sprintf too", because there's no reason it would not work if you do it right. Although that syntax you showed does not look much like perl, more like python or ruby?

my $foo = sprintf("%-30s %18s %18s\n", "$a", "$b", "$c\n");
$result .= $foo;

Upvotes: 2

Related Questions