Rod Burgess wrote:
>
> I am new to the Perl world and am trying to learn it.  A coworker tells me
> that Perl will not work for what I am trying to do however, I think Perl
> would be a great tool to use and  I feel this coworker is wrong.
> I have a file that contains several lines all as below:
> DR03555{tab}    45600062888{tab}     00008FLAT WASHER
> DR03555{tab}    228765329{tab}        00001GASKET
>
> The meaning of the file is
> DR03555 = order number
> 45600062888 = part number
> 00008 = quantity
> FLAT WASHER = Description
>
> The lines all begin with the prefex DR  I would like to read this file and
> produce the following output:
>
> 45600062888;8;FLAT WASHER
> 228765329;1;GASKET
>
> basiclly I need a file that lists the following:
> Part#;Quantity;Description
>
> Is this possible with Perl?

It certainly is. Your colleague is very misguided: this is just the sort of
thing Perl was originally designed for. I have set up a text file with the
contents you describe and the following program produces the results you asked
for:

  use strict;
  use warnings;

  open my $fh, 'file' or die $!;

  while (<$fh>) {
    if (/^(DR\d+)\s+(\d+)\s+(\d{5})(.+?)\s*$/) {
      my ($ordnum, $part, $qty, $desc) = ($1, $2, $3, $4);
      $qty += 0;
      print "$part;$qty;$desc\n";
    }
  }

  close $fh;

OUTPUT

  45600062888;8;FLAT WASHER
  228765329;1;GASKET

The while loop reads and processes each record in the data file. If the line
matches the regular expression (which also extracts the data fields if it is
successful) then the fields are reformatted and printed. The regular expression
is looking for a line that starts with 'DR' followed by at least one digit and
some whitespace; a sequence of one or more digits and some more whitespace; five
digits and then any text to the end of the line, excluding trailing whitespace.
Those four fields go into $1 .. $4 and are copied to named variables. Adding
zero to $qty changes it from a string '00008' to a number 8 to remove the
irrrelevant leading zeroes.

I hope that's clear enough for you.

Rob

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


Reply via email to