Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

grabbing a line from an array 1

Status
Not open for further replies.

moonhead

Technical User
Apr 24, 2002
11
GB
Hi All
i am currently writing a script that reads a file into an array.
i am then doing a search from stdin for a string in the file.
my next task is as follows:
i would like to grab the line of text where the search string is stored and display it on the screen.
including multiple instances
============================================================
my code:
print "\nTo search for a MSISDN please enter the number below...\n";

$msisdn=<STDIN>;

chomp $msisdn;


print &quot;searching...\n&quot;;
sleep 2;

print &quot;searched OUTPUT file:\n&quot;;

$found=0;
foreach (@newarray)
{
print &quot;$_&quot;;
if(/$msisdn/ig)
{
$found=1;
}
}
if($found==1)
{
print &quot;MSISDN has been found\n&quot;;
}
else
{
print &quot;MSISDN is not present in the output file\n&quot;;
============================================================
the file contains:
12:34:56 01420563694 1234 0 60 200 45 2970 1/30 2/0 s60k0t0a0m0c30
12:34:56 billy 01420563694 1234 0 300 200 45 2850 1/150 2/0
12:34:56 01420563694 1234 0 300 236 256 3425 1/300 2/0 s300k0t0a0m0c75
12:00:30 747568002 1234 0 30 330 279 1280 1/20 2/0 s30k0t0a0m0c20
============================================================
the example msisdn i am searching for is:
747568002 (4th line down)
============================================================
i want to grab the line:
12:00:30 747568002 1234 0 30 330 279 1280 1/20 2/0 s30k0t0a0m0c20

if anyone can help i will be very grateful
thanks
moonhead.


 
Can't actually see why your code wouldn't work unless you really did miss the trailing } off the end of your else statement.
 
Hi greadey
the code i have provided will search for a string within the array, not the whole line.
i would like to search for the string from STDIN and return the whole line that the string resides, not just the search string.
 
This will read an input stream line by line and
print the line if it matches your regex:
Code:
while(<IO_HANDLE_GOES_HERE>){
print if /$msisdn/;
$count++;
}
$count ||= &quot;No&quot;;
print &quot;$count occurences...&quot;;

Don't forget to close your filehandle out. Using the <> angle operator (also called the readline operator) is a much better way of iterating over a file line by line rather than copying the file into an array and iterating over the array. Do you REALLY need the whole file in RAM??? Probably not. Just on line at a time.

Hope this helps.

--jim
 
Coderifous
thanks for the prompt reply
i will give it a go
moonhead
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top