pulling data from a file/piping variables to if statement...

A

Adimax

Very new to perl, but not programming in general. What I'm trying to
do is get a dynamically changing file in list format - something like:

apple
orange
pear

and get the code to pull that into an if statement. I've gotten as far
as being able to print the list:

% open (FILE, "/var/www/test");
% my @custom = <FILE>;
% chomp @custom;
% # print "@custom"; # this prints out 'apple orange pear'
% close FILE;

And my if statement works if I define it specifically:

% if ($server eq "apple" or $server eq "orange" or $server eq "pear")
{
display some text
% }
% } # endif $server

However, if I try to use something like:

% # if ($server eq @custom) {
display some text
% }
% } # endif $server

every $server is included in the 'display some text'. I know I'm off
a bit here, but any help or references to examples would be greatly
appreciated.

Benjamin
 
G

George Mpouras

my $server;
my $file_with_servers= './servers';
my $file_to_check = './test';

open FILE, '<', $file_with_servers or die "$^E\n";
while(<FILE>) {chomp; $server{$_}=1}
close FILE;

open FILE, '<', $file_to_check or die "$^E\n";
while(<FILE>) {chomp; print "Server $_ found\n" if exists $server{$_} }
close FILE;
 
J

Jürgen Exner

Adimax said:
And my if statement works if I define it specifically:

% if ($server eq "apple" or $server eq "orange" or $server eq "pear")
{
display some text
% }
% } # endif $server

However, if I try to use something like:

% # if ($server eq @custom) {

@custom is used in scalar context ('eq' implies scalar context for its
arguments). The scalar value of an array is the number of its elements,
i.e. with your sample data you are effectively testing
if ($server eq "3"){
Probably not what you had in mind.
display some text
% }
% } # endif $server

every $server is included in the 'display some text'. I know I'm off
a bit here, but any help or references to examples would be greatly
appreciated.

Your scenario is a FAQ, please see "perldoc -q contain"
How can I tell whether a certain element is contained in a list
or array?
for a far better explanation than I could possibly provide here.

jue
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,001
Messages
2,570,254
Members
46,850
Latest member
VMRKlaus8

Latest Threads

Top