Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

sprintf and arrays 2

Status
Not open for further replies.

chazoid

Technical User
Dec 2, 2002
300
US
Hi all,
This shouldn't be too difficult for you guys.

I just want to format the length of an array using sprintf to add a leading zero:

$total = sprintf("%02d", @files);

for an array with 5 elements this gives me "00" instead of "05". The perl docs say something about arrays not working as you would expect, but it wasn't too clear on it.

for now, I'm just doing this, but is it the only way?

$total = @files;
$total = sprintf("%02d", $total);

Thanks!

justin
 
The problem is that [tt]$total = sprintf("%02d", @files);[/tt] is giving @files an array context, so the format string [tt]"%02d"[/tt] is being applied to the first element of the array. You need to force a scalar context to get the size of the array, which you're doing with [tt]$total = @files[/tt].

You could, instead, do:
[tt]$total = sprintf("%02d", scalar @files);[/tt]

This forces a scalar context for [tt]@files[/tt]
 
ahh... I understand now.. Thanks for the quick reply! I can go home early today :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top