Link to home
Start Free TrialLog in
Avatar of akatsuki27
akatsuki27Flag for United States of America

asked on

Why is 'while loop' not executing

Hey,

I'm writing a perl script where I read a conf file. The conf file is a csv file that has two columns of data. I want to read the first column and match to the host the script is running on and iterate through it's matches. It's clearer when you see the format of the csv file that is like this:

"hostA","host1"
"hostA","host2"
"hostA","host3"
...
"hostB","host1"
"hostB","host2"
"hostB","host3"
...
"hostC","host1"
"hostC","host2"
"hostC","host3"
...

Basically it's a simplified routing table. The first column contains a source host and the second column is the destination it's connecting to.

If the script happens to be on hostA, the loop will find the "to hosts" and print them. Well, really I dont want it to print, I will do another task with the output but for testing purposes, so I know it's working I want to print it. The correct output would be:

The 'to-hosts' for this machine are "host1"
The 'to-hosts' for this machine are "host2"
The 'to-hosts' for this machine are "host3"

But it's not executing the loop. I'm a super newbie to perl, in fact I've never a perl script before so it's learn as I go so I'm not sure why the loop is not executing. Can someone take a look at the code and see what is wrong with it?

Thanks,
Jose

open (F, $file) || die ("Could not open $file");

while ($line = <F>)
{
        ($field1,$field2) = split ',', $line;
        if ($field1 eq $host){
                print "The 'to-hosts' for this machine are $field2\n";
                }
}
close (F);

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Fairlight2cx
Fairlight2cx
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of akatsuki27

ASKER

I figured it out. My conditional was failing because the two sides weren't equal in any of the tests. There were some quotes in one and not the other.

I added the line: $field1 =~ s/\"//g;

That solved it.

Btw Fairlight, I defined $host in the top of the script. But now that I have your attention, could I put that output into an array? Most likely yes. But do I need to do that outside of the while loop?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Harisha M G
Check what is the host name you are getting by printing it:
#!/usr/bin/perl
use Sys::Hostname;
$file = $ARGV[0];
$host = hostname;

open (F, $file) || die ("Could not open $file");

while ($line = <F>)
{
        ($field1,$field2) = split ',', $line;
        print "$field1, $field2, $host";
        if ($field1 eq $host)
        {
                print "The 'to-hosts' for this machine are $field2\n";
        }
}
close (F);

Open in new window