Link to home
Start Free TrialLog in
Avatar of Tolgar
Tolgar

asked on

How to parse a file that has code in it to identify a pattern in Perl?

Hi,
I would like to parse a file and return 1 or 0 based on the following condition:

If there is asterisk "*" in a line that  STARTS WITH "import" then it should return 0.

If there is NO asterisk "*" in a line that STARTS WITH "import" then it should return 1.
 

EXAMPLES:

The parser should return 1 for the following code: (because there is no asterisk in the lines that starts with import.)
import unit.verify
import unit.constraints.IsEqual

int x = 2*3;

Some more code in here

Open in new window


The parser should return 0 for the following code: (because there is asterisk in the lines that starts with import.))
import unit.verify
import unit.constraints.*

int x = 2*3;

Some more code in here

Open in new window



Can you please tell me how I can write this parse in Perl?


Thanks,
SOLUTION
Avatar of whosbetterthanme
whosbetterthanme
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Tolgar
Tolgar

ASKER

Hi,
Thanks for your reply. I have two questions about your solution.

1- In your code how can we make the following addition: (because I don't want to print 0 or 1. Instead, I want to  pass this value (1 or 0) along with the line numbers that has this match to the other Perl code which calls this one.)

open (FILE, $file) or die "Couldn't open $file: $!\n";
my @data = <FILE>;
close(FILE);

foreach my $line (@data) {

    if ($line =~ /^import/ and grep(/\*/,$line)) {
       //print "0\n";
SAVE THE LINE NUMBER IN AN ARRAY
    }
    else {
    //print "1\n";
    }

}

IF THE ARRAY THAT HAS THESE LINE NUMBERS HAS A LENGTH BIGGER THAN ZERO 
THEN PASS THIS ARRAY WITH THE LINE NUMBERS
ELSE PASS 1 WITH AN EMPTY ARRAY

Open in new window


2- Is it possible to write the following line without using grep, but instead just the regular expressions?

if ($line =~ /^import/ and grep(/\*/,$line)) {

Open in new window


Thanks,
ASKER CERTIFIED SOLUTION
Avatar of Fidelius
Fidelius
Flag of Croatia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I believe Fidelous and I have given a
solution