Pam Derks wrote:
> 
> Hi all,

Hello,

> I want to grap the:
> last first middle(if any) email
> from a text file
> 
> sometimes there is a middle intital, sometimes there isn't
> 
> sample data:
> Smith, Mary [EMAIL PROTECTED]
> Jones, Tommy Lee [EMAIL PROTECTED]
> 
> can someone suggest improvements to the code below?
> 
> #!/usr/bin/perl -w

use strict;


> my ($first, $last, $middle, @fields);

You should define these variables in the smallest possible scope instead
of at the top of the program.

> open(IN, "text.txt") or die("nope: $!\n");
> while($line = <IN>){

while ( my $line = <IN> ) {


>         chomp($line);
> 
>         @fields=split(/ /, $line);

split / / will split using a single space, it is more efficient to use
the default.

          my @fields = split ' ', $line;


>         #an array in scalar context returns number of elements
>         $number = @fields;
>         print("number: $number\n");
> 
>         #if there is no remainder, there are 3 elements
>         if($number % 3 == 0){

Why use modulus, just use == 3.

          if ( @fields == 3 ) {


>                 $first = $fields[0];
>                 $last = $fields[1];
>                 $email= $fields[2];

According to your explaination at the beginning the order of the names
is "last first middle(if any)".  So is that the correct order or is it
really "first last"?  Also, since you declared $middle outside of the
loop, the value in $middle will not be changed here.  If the previous
record had a middle name that middle name will show up in subsequent
records that have no middle name.


>         }
> 
>         #if there is no remainder, there are 4 elements
>         elsif($number % 4 == 0){

          elsif ( @fields == 4 ) {


>                 $first = $fields[0];
>                 $last = $fields[1];
>                 $middle= $fields[2];
>                 $email= $fields[3];
>         }
> 
>         print("first: $first\n");
>         print("last: $last\n");
>         print("middle: $middle\n");
>         print("email: $email\n");
> }
> 
> close(IN);


This is the way I would do it:

#!/usr/bin/perl -w
use strict;

open IN, 'text.txt' or die "Cannot open 'text.txt' $!";

while ( <IN> ) {
    # split removes ALL whitespace so chomp isn't required
    my @fields = split;
    print 'number: ' . @fields . "\n";

    my $email  = pop   @fields || '';
    my $last   = shift @fields || '';
    my $first  = shift @fields || '';
    my $middle = shift @fields || '';

    print "first: $first\n";
    print "last: $last\n";
    print "middle: $middle\n";
    print "email: $email\n";
}

close IN;

__END__



John
-- 
use Perl;
program
fulfillment

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

Reply via email to