Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl appending (s)printf output to string

Tags:

perl

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

like image 278
user1610717 Avatar asked Mar 18 '13 22:03

user1610717


2 Answers

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(...);
like image 128
ikegami Avatar answered Nov 15 '22 08:11

ikegami


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;
like image 45
TLP Avatar answered Nov 15 '22 08:11

TLP