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 derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

parsing file, splitting variable lines into scalars 1

Status
Not open for further replies.

nfaber

Technical User
Joined
Oct 22, 2001
Messages
446
Location
US
Hello all,

I have a text file I need to split up into scalars. The format of the text file is:

Code:
Company Key            Company Name               Exceptions

abc,                    ABC Company,
def,                    DEF Company,              HIJ KLM
nop,                    NOP Company,              QRS


what I need is to break each line into scalars and if there is any Exceptions, break them into scalars, if not do something else.

Something like

Code:
while <FILE>
    chomp;
    next if /^Company Key/;
    if (/\w{2,3},\s+\w+\s+,\w+/) {
       ($key,$company,$exception1,$exception2,etc.) = split (/,/);
    }else{
        ($key,$company) = split (/,/);
    }

My problem is there could be any number of exceptions or no exceptions for each company, and I need to assign each exception to a different scalar.

I have some flexability over the format of the file I am processing.

Thanks for any help,

Nick
 
... there could be any number of exceptions or no exceptions for each company, and I need to assign each exception to a different scalar.
It isn't possible to declare "any number" of scalar variables, since you don't know how many you'll need.
How about assigning the exceptions to an array? Then you can do whatever you want with the individual elements. E.g.
Code:
#!perl
use strict;
use warnings;

while (<DATA>) {
    chomp;
    next if /^Company Key/ || /^\s*$/;
    my ($key, $company, $exceptions) = split /,\s*/;
    my @exceptions = split /\s+/, $exceptions;
    printf "%-20s%-20s%-20s\n", $key, $company, join(" ", @exceptions);
}

__DATA__
Company Key            Company Name               Exceptions

abc,                    ABC Company,
def,                    DEF Company,              HIJ KLM
nop,                    NOP Company,              QRS
HTH


 
Code:
BEGIN { FS=",[ \t]*" }
NF>1 { printf "%-9s%-20s%s\n", $1, $2, $3
  if ( split($3,excep," +"))
  { for (i=1; i in excep; i++)
      process( excep[i] )
  }
}
 
... Or we could wait for AWKman ...

--Paul

I'm assuming AWK is more powerful than MAN ;)

cigless ...
 
I like your idea Mike. The exceptions seem made for an array. I'll try it.

Thanks


PS: I expect the "AWKman" any time now.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top