Im looking to put a loop into a program i have created but right now it only runs on a static IP hardcoded in the program. I would like it to loop through a list of IP addresses from a CSV file and loop until all IP have been used. Has anyone here done this or can point me in the right direction?

Something like this?

use strict;
use warnings "all";

my @ip;
open my $IN, "<csv.txt" or die "cannot open file to read.\n";
while(<$IN>)
{
    @ip = split(",", $_);
}
close $IN;

foreach(@ip)
{
    print "$_\n";
}

We read the data from a file and then loop through it.

Edited 4 Years Ago by replic: reason

So if i had my program like this:

send();

sub send{
my @ip;
open my $IN, "<csv.txt" or die "cannot open file to read.\n";
while(<$IN>)
{
@ip = split(",", $);
}
close $IN;
foreach(@ip)
{
print "$
\n";
}

my main code will go here. it will take an IP from above and repeat the process untill all the IP's have been used.

}

I assume your file looks something like: "value,value,value" and has no newlines. In this case we can change the code a bit.

use strict;
use warnings "all";

my @ip;
open my $IN, "<csv.txt" or die "cannot open file to read.\n";
@ip = split(",", <$IN>);
close $IN;

foreach(@ip)
{
    print "$_\n"; # do something with the IP here
}

Take a look at the foreach loop now. In there you can do whatever you want with the current IP, the print is just an example which can be replaced by whatever you need to do. You don't need to call all of this in a function because all the IPs are already stored in the array, so you just need to loop through it.

The code below will do what you wanted, please feel free to ask any question.
NOTE: DO NOT use send as your subroutine name, as perl has a function called send. Do perldoc -f send to check it.

#!/usr/bin/perl
use strict;
use warnings;

open my $fh, '<', 'csv.txt' or die "cannot open file to read:$!";
while ( defined( $_ = <$fh> ) ) {
    foreach my $ip ( split /\s+|,/, $_ ) {
        send_it($ip);    ## calls subroutine send_it to use each of the ip
    }
}
close $fh;

sub send_it {
    my ($ip_to_use) = @_;
    print $ip_to_use, $/;    ## do something with your Ip here
    return;
}
This article has been dead for over six months. Start a new discussion instead.