Amit Saxena wrote:
> 
> On Mon, Jul 14, 2008 at 8:23 PM, vikingy <[EMAIL PROTECTED]> wrote:
> 
>> There is a file  created likes this:
>>
>>   open File ">file.txt" or die $!;
>>   foreach .. <..> {
>>      printf File "%5d %11.2f\n", $data1,data2;
>>   }
>>   close File;
>>
>> and my question is, how to read these data follow the same format as "%5d
>> %11.2f' from this file again?
>>    thanks in advance!
>
> #! /usr/bin/perl
> 
> use warnings;
> use strict;
> 
> open (PTR1, "<filename.txt") or die "Unable to open file filename.txt :
> $!\n\n";
> 
> while (chomp ($str = <PTR1>))

That will exit the loop if an empty line is encountered before the end of the
file, and will throw a warning at the end of the file because of chomp having an
uninitialized value

  while (my $str = <PTR1>) {
    chomp $str;
      :
  }

> {
>       sscanf($str, "%5d %11.2f", $data1, $data2);
> 
>       # do whatever processing.....
> }
> 
> close (PTR1);

There is really no point in forcing a format onto the incoming data lines. If
there's a need to validate the format of the records then regular expressions
are the tool to use.

  while (<PTR1>) {
    my ($data1, $data2) = split;
  }


is all that is needed.

HTH,

Rob

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to