-2

I have the following code and I want the output to .txt file so can someone pls help to print the output Into some file ? Rather It should have an option for a user to push to file or print to the command prompt Itself.

# Opening Keyword File here
open( my $kw, '<', 'IMSRegistration_Success_MessageFlow.txt') or die $!;
my @keywords = <$kw>;
chomp(@keywords); # remove newlines at the end of keywords

# post-processing your keywords file for adding comments
my $kwhashref = {
  map {
    /^(.*?)(#.*?#)*$/;
    defined($2) ? ($1 => $2) : ( $1 => undef )
  } @keywords
}; 

# get list of files in current directory
my @files = grep { -f } (<*main_log>,<*Project>,<*properties>);
# loop over each file to search keywords in
foreach my $file (@files) 
{
    open(my $fh, '<', $file) or die $!;
    my @content = <$fh>;
    close($fh);
    my $l = 0;

    foreach my $kw (keys %$kwhashref) 
    {
        my $search = quotemeta($kw); # otherwise keyword is used as regex, not literally
        foreach (@content) 
            { # go through every line for this keyword
                $l++;
                if (/$search/)
                    {
                        print $kwhashref->{$kw}."\n" if defined($kwhashref->{$kw}) ;
                        printf 'Found keyword %s in file %s, line %d:%s'.$/, $kw, $file, $l, $_
                    }
            }
    }
}
rocky
  • 23
  • 5
  • 1
    What have you tried to do yourself, and what problem did you encounter? We can't help you very easily if you don't describe what went wrong. – Borodin Feb 06 '17 at 05:48
  • `print $fh ...` and `printf $fh ...`, but it's more flexible to just lest the caller redirect the output (`script.pl >output.txt`) – ikegami Feb 06 '17 at 06:54
  • when I use the command perl Test.pl > my_output.txt I can get the output Into my file outout.txt but i want to Incorporate It within the script . something like using the system command. – rocky Feb 06 '17 at 06:58
  • http://stackoverflow.com/questions/2907593/how-can-i-redirect-standard-output-to-a-file-in-perl check the second answer of this question – John Doe Feb 06 '17 at 12:01
  • That's quite complicated code, given that this question is about writing to a file. Did you write it and are you having problems modifying it, or ... is it someone else's code that you're asking the internet to fix? – Sobrique Feb 06 '17 at 14:41
  • @John Doe .. Thanks – rocky Feb 17 '17 at 13:37

2 Answers2

0
script.pl >output.txt

ikegami
  • 367,544
  • 15
  • 269
  • 518
  • I can use from the command prompt but I want to Incorporate It Within the Script Itself. e.g. using some system() commands etc. – rocky Feb 06 '17 at 07:00
0

I can get the output Into a file using below code:

print $out_file $kwhashref->{$kw}."\n" if defined($kwhashref->{$kw}) ; printf $out_file 'Found keyword %s in file %s, line %d:%s'.$/, $kw, $file, $l, $_;

rocky
  • 23
  • 5