Training, Open Source computer languages
PerlPHPPythonMySQLApache / TomcatTclRubyJavaC and C++LinuxCSS 
Search for:
Home Accessibility Courses Diary The Mouth Forum Resources Site Map About Us Contact
Loops

Posted by matt (matt), 3 March 2003
Graham

Thanks for a great course.

I am having troublke with a piece of code (see below). I have written a small program that allows me to type in an IP and then the program checks it against a file and then prints some fields. My question is how do I now get this to repeat itself, what I really want is to type in several if not dozens of IPs and then the program prints all of the details in the file Hosts.lst. Please help................................

#!/usr/bin/perl

print "which file ? \n";

open (FH, <STDIN>);

open (FHA, ">Hosts.lst");

print "enter ip ";
chomp ($ipvalue = <STDIN>);

foreach $line(<FH>) {

@parts = split (/,/,$line);


if ($ipvalue =~ $parts[2]) {

print FHA "$parts[2] $parts[7] $parts[24] $parts[25]\n";

next;

}

}



Posted by admin (Graham Ellis), 3 March 2003
Example answer follows ... I've added an extra loop that keeps going round while you provide data; just pressing return will cause the program to exit.   I've also read all the data from the file into a list at the start of the program to avoid having to read it many times over.   This assumes that the input file is not enormous and can fit into available memory.

Code:
#!/usr/bin/perl

print "which file ? \n";
chomp ($file = <STDIN>);    # Added a chomp to get rid of \n
open (FH, $file);  
@sourcedata = <FH>;         # Added read of whole file into list
open (FHA, ">Hosts.lst");

while (1) {                 # Extra loop to step through use inputs
       print "enter ip ";
       chomp ($ipvalue = <STDIN>);
       last unless ($ipvalue);                 # Exit from loop if no more data
       foreach $line(@sourcedata) {            # From list not direct from file
               @parts = split (/,/,$line);
               if ($ipvalue =~ $parts[2]) {
                       print FHA "$parts[2] $parts[7] $parts[24] $parts[25]\n";
                       next;
               }
       }
}                           # End of extra loop





This page is a thread posted to the opentalk forum at www.opentalk.org.uk and archived here for reference. To jump to the archive index please follow this link.

© WELL HOUSE CONSULTANTS LTD., 2009: Well House Manor • 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01144 1225 708225 • FAX: 01144 1225 707126 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho