Click to See Complete Forum and Search --> : Perl Problem: Number formation


NoHero
January 2nd, 2005, 02:24 PM
Hi guys

I just tried to get a small introduction into perl and now I am facing a little problem:

In C you can use the printf() to do number formations. Such as adding nulls to the front until a maximum length is reached:


for ( int i = 1; i < 15
printf("%02d", number);


Will result in 01, 02, 03, 04 etc. But how can I do this in PERL?

I have the following script:


#!/usr/bin/perl

use warnings;
use strict;
use diagnostics;

use LWP::Simple;

print "Content-Type: text/html\n\n";

for my $index(1..14)
{
my $filename='http://www.aperfectcircle.com/posters/poster'.$index.'.jpg';

print "$filename\n";
my $bild= get($filename);

if(defined $bild)
{
open DAT,'> C:/apc/'.$index.'.jpg';

binmode DAT;
print DAT $bild;

close DAT;
}
}


I need the formation in the bold line, because the files are named poster01.jpg, poster02.jpg and so on.

Any help would be very appreciated!
Thanks, Florian

visualAd
January 3rd, 2005, 05:47 AM
I had to solve a similar problem when I wrote a bash script a short time ago. What you need to do is treat the $index variable as a string and text its length. If it is less than the numbr of zeros then left pad it with zeros to make it the correct length.

I don't know how you do this in Perl though. :ehh:

NoHero
January 3rd, 2005, 08:36 AM
I had to solve a similar problem when I wrote a bash script a short time ago. What you need to do is treat the $index variable as a string and text its length. If it is less than the numbr of zeros then left pad it with zeros to make it the correct length.

I don't know how you do this in Perl though. :ehh:

Me either. But does the Perl not provide any function that may solve this problem?
Thank you for help though.

visualAd
January 3rd, 2005, 08:47 AM
I am sure there is, but I am not a perl programmer. A quick google search has produced this article:

http://www.pageresource.com/cgirec/ptut13.htm

So you could give this code a try:

if (length($index) < 2) $num = '0' . $index;

my $filename='http://www.aperfectcircle.com/posters/poster'.$num.'.jpg';

NoHero
January 3rd, 2005, 09:09 AM
Ok I got it ...


#!/usr/bin/perl

use warnings;
use strict;
use diagnostics;

use LWP::Simple;

print "Content-Type: text/html\n\n";

for my $index(1..14)
{
my $num = $index;
my $filename = "";

if (length($index) < 2)
{
$num = '0'.$index;
}
$filename = 'http://www.aperfectcircle.com/posters/poster'.$num.'.jpg';

print "$filename\n";
my $bild= get($filename);

if(defined $bild)
{
open DAT,'> C:/apc/'.$index.'.jpg';

binmode DAT;
print DAT $bild;

close DAT;
}
}


Works perfect, thank you visualAd!

/ by the way you should run it and take a look at the posters ;)
// or simply visit www.aperfectcircle.com

khp
January 3rd, 2005, 02:13 PM
Ehh perl has both printf and sprintf functions, which works in the same way as in C.

When you refuse to look for something you will never find it.