• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 257
  • Last Modified:

CGI-PERL and grep

I'm pretty new to Perl and I have a file and I would like to search it for the number 27& at the beginng of a line and store that line in a variable.  I have it something like this, unforutunately it's not doing it correctly.

open(FILE,"<test.txt") or die;
flock(FILE,2);
$line = grep /^27&/, <FILE>;
close FILE;

0
kevin_ma
Asked:
kevin_ma
  • 4
  • 3
1 Solution
 
TintinCommented:
open FILE, "test.txt" or die "Can not open test.txt $!\n";

while (<FILE>) {
  if (/^27&/) {
     $line=$_;
      last;
   }
}
0
 
kevin_maAuthor Commented:
Thanks for the reply Tintin, you happen to know how to do it with grep?
0
 
TintinCommented:
@line = grep /^27&/,<FILE>;

In the scalar context ($line) , grep returns the number of matches.  You need to use an array to store the actual matches.
0
Learn to develop an Android App

Want to increase your earning potential in 2018? Pad your resume with app building experience. Learn how with this hands-on course.

 
kevin_maAuthor Commented:
Thanks, I'll give you the points.  For the

@line = grep /^27&/, <FILE>;

can you put a variable inside? for example

$num=27;
@line = grep/^\$num/, <FILE>;  # i tried it, with and without the escaping tho it's not producing the results I want.

or for the top one

$num=27;
while (<FILE>) {
  if (/^\$num&/) {
     $line=$_;
      last;
   }
}

Appreciated.
0
 
TintinCommented:
Should be:

@line = grep /^$num&/, <FILE>;

Putting a \$ means to search literally for a $ symbol.
0
 
kevin_maAuthor Commented:
Yea I tried that too, but it's not working.  I tried both with an array and the other method u suggested with the while loop it doesn't seem to work.
0
 
kevin_maAuthor Commented:
Nevermind I figured it out. Thanks.
0

Featured Post

[Webinar] Improve your customer journey

A positive customer journey is important in attracting and retaining business. To improve this experience, you can use Google Maps APIs to increase checkout conversions, boost user engagement, and optimize order fulfillment. Learn how in this webinar presented by Dito.

  • 4
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now