First time poster and my first time trying to script in Perl so be gentle with me.
What I need to do is read a log file that contains ip's and port numbers. The contents of the file are:
6056 255.255.255.255 6056 255.255.255.255 80
16056 255.255.255.255 160开发者_高级运维56 255.255.255.255 80
7056 255.255.255.255 7056 255.255.255.255 80
17056 255.255.255.255 17056 255.255.255.255 80
The file contains more entries like this.
The first value of every line needs to be extracted and added to a variable $LocalPort
, the second value of every line assigned to $LicenseServer
, third value $RemotePort
, fourth value $ShServer
, fifth value $ShServerport
.
At the end of every loop values are will be inserted into $command
variable and written to a file that can be run as a script to establish a vsh connection. I can read in the file just fine but I am unsure of how to extract each value and assign it to the appropriate value each time it goes threw the loop. I currently have this:
open (LOGFILE, $LogPath) || "Unable to open the log file or file does not exist $!";
while (@line = <LOGFILE>)
{
$LocalPort=$line[0];
$LicenseServer=$line[1];
$RemotePort=$line[2];
$ShServer=$line[3];
$ShServerpor=$line[4];
print "$LocalPort\n";
print "$LicenseServer\n"
print "$RemotePort\n";
print "ShServer\n";
print "ShServerPort\n";
}
So far all I can get it to do is spit back the exact file as it reads it in. This is really my first attempt at scripting and I have no training other then what I can gather from lord Google. Any help is much appreciated.
@line = <LOGFILE>
reads the entire file into @line
. What you need is something like this:
while (<LOGFILE>) {
( $LocalPort, $LicenseServer,
$RemotePort,$ShServer,$ShServerpor ) = split (/\s/, $_ );
}
use strict;
use warnings;
while(<>) {
chomp;
next if /^\s*$/; #skip empty lines
my($local_port, $license_server, $remote_port, $sh_server, $sh_server_port) = split;
print "$local_port\n";
#....
}
use as
perl my_script.pl < file_with_data.txt
or
perl my_script.pl file_with_data.txt
Welcome Dan to stackoverflow.
#!/usr/bin/perl
# ALWAYS declare these two lines
use strict;
use warnings;
my $logPath = '/path/to/logfile';
# use 3 args open and test for failure
open my $fh, '<', $logPath or die "unable to open '$logPath' for reading: $!";
# read one line at a time
while(my $line = <$fh>) {
# delete line separator
chomp $line;
# split each line on spaces
my ($LocalPort, $LicenseServer, $RemotePort, $ShServer, $ShServerpor) = split/\s+/, $line;
# do the stuff with the variables
}
#close the file and test for failure
close $fh or die "unable to close '$logPath' : $!";
精彩评论