perl if statement

Hello guys,

I was wondering why my code doesn't read a variable when using if statement as follows:

$userlist='users.txt';
$user='b999';
                open (ACTULOG, ">>$userlist");
                print ACTULOG "$user\n";
                close (ACTULOG)

this will work and prints b999 into users.txt file
BUT

$userlist='users.txt';
$user='b999';
$grepinfo=`/usr/bin/grep -w $user $userlist`;
        if ($user = $grepinfo) {
       exit ;
        } else {
                open (ACTULOG, ">>$userlist");
                print ACTULOG "$user\n";
                close (ACTULOG)
                }

wont work and it will prints empty line into users.txt if b999 does not exists! it should print b999 into the file if doesn't exists and if exists it will exit safely.

any idea why the line print ACTULOG "$user\n"; isn't possible to read the $user variable?

Thanks.

You assigned to $user in the "if" test:

if ($user = $grepinfo) {

If the grep fails, no output is dumped to $grepinfo, which got assigned to $user. So you get an empty line when you print() it.

Basically the above if stmt is checked against 'true' always .....
as u are assigning grepinfo value to user.

so .. evry time u are 'exit' ing out ....;

Do string comparision using 'eq' opearaor in perl.

Check the following link .....

i was able to change the if statement to
if ( $grepinfo =~ /$user/ ) and worked just fine :slight_smile:

Thanks for the advice guys.