Home: Perl Programming Help: Beginner:
Reading a list of names into a variable - config file?



regex2012
User

Oct 10, 2017, 12:36 PM


Views: 1789
Reading a list of names into a variable - config file?

Now I have a very easy script like this (It will be developed into a script that launches various commands against the host:

Code
chomp( my $strHostname = qx{ hostname }); 

if ($strHostname eq "milkbottle") {
print "yes";
} else {
print "no";
}

Is there any way to use a separate file to read into the $strHostname variable? I have 50 hosts that need to go into this condition, is it possible? It would be easy if people could just open the file and add hostnames as they needed.


BillKSmith
Veteran

Oct 11, 2017, 4:18 AM


Views: 1775
Re: [regex2012] Reading a list of names into a variable - config file?

Your requirement is not clear. I think you want a program that will tell you if the current host is one of the ones named in a file.

The following code reads the possible names from the file named on the command line (defaults to an internal memory file). It then uses a module to test if the hostname matches any of those names.


Code
use strict; 
use warnings;
use List::MoreUtils qw(any);
my $input_file = $ARGV[0] // \do{
"milkbottle\n"
."beerbottle\n"
."milktoast\n"
};

open my $FH, '<', $input_file or die "Cannot open input\n$!";
my @hosts = <$FH>;
chomp @hosts;

my $strHostname = qx{ hostname };

print( ( any {$strHostname eq $_} @hosts ) ? 'yes' : 'no' );

Good Luck,
Bill