Premchand Premchand -4 years ago 50
Perl Question

Print variable after closing the file in Perl

Below code works fine but I want

$ip
to be printed after closing the file.

use strict;
use warnings;

use POSIX;

my $file = "/tmp/example";

open(FILE, "<$file") or die $!;

while ( <FILE> ) {

my $lines = $_;

if ( $lines =~ m/address/ ) {
my ($string, $ip) = (split ' ', $lines);
print "IP address is: $ip\n";
}
}

close(FILE);


sample data in /tmp/example file

$cat /tmp/example
country us
ip_address 192.168.1.1
server dell

Answer Source

Store all ips in an array and you'll then have it for later processing. The shown code can also be simplified a lot. This assumes a four-number ip and data like that shown in the sample

use warnings;
use strict;
use feature 'say';

my $file = '/tmp/example';
open my $fh, '<', $file or die "Can't open $file: $!";

my @ips;

while (<$fh>) {
     if (my ($ip) = /ip_address\s*(\d+\.\d+\.\d+\.\d+)/) {
         push @ips, $ip;
     }
}
close $fh;

say for @ips; 

Or, once you open the file, process all lines with a map

my @ips = map { /ip_address\s*(\d+\.\d+\.\d+\.\d+)/ } <$fh>;

The filehandle is here read in a list context, imposed by map, so all lines from the file are returned. The block in map applies to each in turn, and map returns a flattened list with results.

Some notes

  • Use three-argument open, it is better

  • Don't assign $_ to a variable. To work with a lexical use while (my $line = <$fh>)

  • You can use split but here regex is more direct and it allows you to assign its match so that it is scoped. If there is no match the if fails and nothing goes onto the array

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download