1

I am new to perl programming. I have a scenario where a username is entered in a file, lets say info.log. So, now I want to check whether this username is present in the file contents or not

 $user = $ENV{USER};
 open (READ_USER_INFO_LOG, "info.log") || die("-E- Unable to open \"info.log\n");
          @content = <READ_USER_INFO_LOG>;
          close READ_USER_INFO_LOG;
          foreach $line(@content)
          {
             if($line has $user)
             {
                  print "Usenrmae found";
                   break;
             }
           }
Rajeev
  • 44,985
  • 76
  • 186
  • 285

3 Answers3

7

Okay, a few things:

  1. Always, always, always use strict; and use warnings;. Each and every single time.
  2. Bareword filehandles are bad. Use a three argument open:
    open(my $read_user_info_log,"<","info.log") or die "-E- Unable to open \"info.log\"\n";
  3. $line has $user doesn't mean anything. Instead, you can check each line via a regular expression: if($line=~/$user/){...}
  4. Perl's equivalent of break is last.
  5. You may also want to chomp the lines of your file to remove the trailing end of line characters:
    chomp(my @content=<$read_user_info_log>);

Honestly, I'd recommend reading the (newly released) sixth edition of Learning Perl.

Community
  • 1
  • 1
1

I think you may want to change the line:

 if($line has $user)

to

 if ($line =~ /$user/)

This way, a regular expression will search the line for $user anywhere within it.

EMiller
  • 2,792
  • 4
  • 34
  • 55
0
 $user = $ENV{USER};
 open (READ_USER_INFO_LOG, "info.log") || die("-E- Unable to open \"info.log\n");
          @content = <READ_USER_INFO_LOG>;
          close READ_USER_INFO_LOG;
          foreach $line(@content)
          {
             if($line =~ /$user/)
             {
                  print "Usenrmae found";
                   break;
             }
           }
Matt Healy
  • 18,033
  • 4
  • 56
  • 56