in reply to Re^2: Matching part of a line and saving it into a variable
in thread Matching part of a line and saving it into a variable

Assuming the output you want is:
Lawrence, Jerry A. Wallace, Bob W. Anthony, Ronald Nelson, Dwight R. Jamison, Jeff S. Favors, Eric S. Williams, Herb C. Carter, Shaun


This code works
#!/db/bin/perl -w use strict; use warnings; my $filename = $ARGV[0]; open FILE, $filename or die $!; my $i = 0; while(<FILE>) { if($i == 0) { $i++; next; } chomp; if (/\"(.*?), (.*?)[" ]((.*?)\")?/) { my $last = $1; my $first = $2; my $mi = $4; if(defined $mi) { print "$last, $first $mi\n"; } else { print "$last, $first\n"; } } } close FILE;

Replies are listed 'Best First'.
Re^4: Matching part of a line and saving it into a variable
by mistamutt (Novice) on Mar 14, 2011 at 20:35 UTC
    That works awesomely! May I ask, what the first if clause does?

    if($1 == 0)

    I took the regex match and the printing code and replaced the code I had before and it worked marvelously, thanks so much. Now I need to play with the $last $first $mi variables and figure out how to output them into a javascript array. I might be back later on this evening unless I can figure it out.
      You stated that you didn't want to print the first line. Notice the variable $i is initialized to 0. That if clause checks if the variable $i is equal to 0. Since we initialized it to 0, it enters the clause. The first line increases the variable $i to 1. Then it tells the while loop to skip to the next iteration. Now when you come to the clause this time, it skips it and continues to the rest of the while code because variable $i now equals 1.

      By the way, glad you're asking questions. The more you ask now, the less you'll ask in the long run.
Re^4: Matching part of a line and saving it into a variable
by CountZero (Bishop) on Mar 14, 2011 at 22:01 UTC
    Double quotes are not magic in a regex, so you do not have to escape them.

    If you want to skip the first line of your loop, why not simply do a <FILE> just before the loop? That reads the first line and discards it.

    You do not need a chomp inside the loop. Your regex extracts the fields well before it reaches the end of the string.

    Always use a three argument open. What do you think will happen when someone maliciously enters >myfile.txt as the filename argument? Indeed, bye bye file contents!

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

      Good points. 3/4 of them were due to me copying the OP's code with barely a glance.