Hi Tim.

Sorry, but may I mess with your code? :)

Tim Johnson wrote:
>
> Zary Necheva wrote:
> >
> > I have a file with data similar to this
> > ..........
> > Exxxxx|FExxxxx|NQxxxxxx|OUxxxxxx|GExxxxxx|OVxxxxxxx|IQxxxxxxxx|ORxxxx
> > Exxxxx|FExxxxxx|NQxxxxxx|GExxxxxxx|OVxxxxxx|OUxxxxxx|IQxxxxxxx|ORxxx
> > Exxxxx|FExxxxxxx|NQxxxxxx|OUxxxxxx|OVxxxxxxx|ORxxxxxxx|IQxxxxxxx|RFxx
> > Exxxxx|FExxxxxx|NQxxxxxx|GExxxxxxx|OUxxxxxx|IQxxxxxxx|ORxxxxxxxx
> > .........
> >
> > I would like to extract only these fields that start with E, FE,
> > NQ, IQ and OU or to have this output
> >
> > ..........
> > Exxxxx|FExxxxx|NQxxxxxx|IQxxxxxx|OUxxxxxx
> > Exxxxx|FExxxxx|NQxxxxxx|IQxxxxxx|OUxxxxxx
> > Exxxxx|FExxxxx|NQxxxxxx|IQxxxxxx|OUxxxxxx
> > Exxxxx|FExxxxx|NQxxxxxx|IQxxxxxx|OUxxxxx
> > ......
>
> This is a pretty classic example of where split and join come in
> handy.  Here I'm reading each line, splitting it into fields by the
> pipe character, then creating a new array with only those fields that
> begin with the letters I specify.  Then I use join to make a string
> with those fields I chose delimited by pipes again.  There may be more
> streamlined ways to do the rest of it, but this is the essence of why
> the split and join functions are there.
>
> use strict;
> use warnings;
> open(INFILE,<myfile.txt")|| die "could not open file for reading!\n";
> while(<INFILE>){
> chomp $_;
> my @fields = split(/\|/,$_);
> my @output;
> foreach my $field(@fields){
> if($field =~ /^(E|FE|NQ|IQ)/){
> push @output,$field;
> }
> }
> print join('|',@output)."\n";
> }

This won't compile as it is, because of the mismatched quote in the
open.

My changes below fix that, as well as using the default $_ variable
within the while loop and substituting a 'grep' call for the
'foreach' loop.

In addition, I'd warn that the field prefixes aren't being terminated
properly. We don't know the nature of the 'xxxxx' stuff, but I would
guess that it's numeric, in which case changing the regex to

  /^(E|FE|NQ|IQ)\d/

will fix that. If not then perhaps you'd let us know Zary?

HTH,

Rob


use strict;
use warnings;

open INFILE, 'myfile.txt' or die $!;

while (<INFILE>) {
  chomp;
  my @fields = split /\|/;
  my @output = grep /^(E|FE|NQ|IQ)/, @fields;
  print join('|', @output), "\n";
}

**OUTPUT

Exxxxx|FExxxxx|NQxxxxxx|IQxxxxxxxx
Exxxxx|FExxxxxx|NQxxxxxx|IQxxxxxxx
Exxxxx|FExxxxxxx|NQxxxxxx|IQxxxxxxx
Exxxxx|FExxxxxx|NQxxxxxx|IQxxxxxxx



-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to