I try to Search for xp_cmdshell string in log.txt file but i got error?

my $file = "c:/logdata.txt";
open (IN,$file) or die "Can't read $file: $!";
my $tag = "xp_cmdshell";
open(IN,"<",$file) || die "could not open $file: $!\n";
while (<IN>) {
    if (grep(/$tag/,$_)) {
    #Do something
3 Years
Discussion Span
Last Post by tony75

Hi tony75,

1.What error message are you getting.
2.Check your filehandle "IN" you used. You can't be reading FROM and writing TO the same filehandle, like you are doing.
3.Also use a 3-arugment for open function. like

open my $fh,'<',$file_to_read or die "can't open file: $!";
 close $fh or die "can't open file: $!";

4.Use lexically scoped filehandle like $fh in the code above.

Please see perldoc -f open frm your CLI
Hope this helps

Edited by diafol: fixed formatting


Thanks Sir,
How can I navigate to my log.txt file on my C:\ driver ?

my $file = shift || die " Enter file name \n";
die "File not found!\n" unless (-e $file);
my $tag = "xp_cmdshell";
open(FH,"<",$file) || die "could not open $file: $!\n";
while (<FH>) {
    if (grep(/$tag/,$_)) {
    #Do something

Edited by tony75


Hi tony75,
Yes that should work, but you can also do like so:

use warnings;
use strict;

my $filename = "";
do {
    print "Enter  file name: ";
    ## get name from the user from CLI
    chomp( $filename = <STDIN> );
    warn "File not Found\n" if !-e $filename;
} while ( $filename eq '' or !-e $filename );

my $tag = "xp_cmdshell";

open my $fh, "<", $filename or die "could not open $filename: $!\n";
while (<$fh>) {
    if ( grep( /$tag/, $_ ) ) {

        #Do something

close($fh) or die "can close file: $!";

It's good practice to always use a lexical scope filehandle like I did, than using a BAREWORD like FH, which is global as filehandles. Then always check for the return of close function just like open function.

Check the usage of the do/while, which enable the user to provide a "workable" filename from the CLI. Please note that, I didn't include a way out, except a correct filename is used. That you could do.
There are more than one way do it though.

You could also check these modules Getopt::Long or Getopt::Std. Just use perldoc Getopt::Long

Edited by 2teez

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.