1

I currently have some code which returns a sites header content back:

#!/usr/bin/perl 

use strict;
require IO::Socket; 

my @header; 
my $host = shift;

my $socket = new IO::Socket::INET(
    PeerAddr => $host, 
    PeerPort => 80, 
    Proto => 'tcp') || die "Could not Connect $!\n"; 

print "Connected.\n"; 
print "Getting Header\n"; 

print $socket "GET / HTTP/1.0\n\n"; 
my $i = 0; 
while (<$socket>) { 
    @header[$i] = $_; 
    $i++; 
} 

$i = 0;
print "--------------------------------------\n"; 
while ($i <= 8) { 
    print "@header[$i++]"; 
} 

print "-------------------------------------\n"; 
print "Finished $host\n";

What I would like to do, is to be able to read from a file open (FILE, '<', shift); and then every IP in the file, to pass into a the header retrieve loop, which saves me from manually doing one by one.

What I mean by this is to have a file containing (example ips): 1.1.1.1 2.2.2.2 on each line and then parsing all of them through the get header function.

2
  • You should really add use warnings and tidy up all the warnings you'll get when you run your code again. Doing things like @header[$i] = $_ probably isn't what you want to do. Commented Feb 9, 2012 at 21:51
  • Just to point out there is a subtle error with the creation of $socket using || as described by @Ilmari Karonen here stackoverflow.com/a/9221648/1190901 Commented Feb 10, 2012 at 2:27

2 Answers 2

1

Replace

my @header; 
my $host = shift;
...

with

while (<>) {
   chomp( my $host = $_ );
   my @header; 
   ...
}
Sign up to request clarification or add additional context in comments.

Comments

1

You would just open your file, read the contents into a list, then iterate over the list:

open my $fh, '<', $file or die "$!";
my @ips = <$fh>;
close $fh;
foreach my $ip ( @ips ) {
   chomp $ip;
   ...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.