http://www.perlmonks.org?node_id=1006948

starface245 has asked for the wisdom of the Perl Monks concerning the following question:

In my folder I have 8 text files and each of those files I want to do hex string search of "hello"
In my folder:
test.txt
test1.txt
foo2.txt
boo3.txt
bar4.txt
fish5.txt
cat6.txt
dog7.txt
I would the output
test.txt match
test1.txt match
foo2.txt not match
boo3.txt match
bar4.txt match
fish5.txt not match
cat6.txt notmatch
dog7.txt match
So far, it only does output = "test.txt match" no other ouputs.
#!/usr/bin/perl use strict; my @files =glob ("*.txt"); my $hex_out = "hex.txt"; for my $file(@files) { open (HEX_IN, "$file") or die; open (HEX_OUT, ">$hex_out") or die; binmode(HEX_IN); binmode(HEX_OUT); local $/; my $hex_string = <HEX_IN>; if ($hex_string =~ /\hello/) { print HEX_OUT "$file"; print HEX_OUT " match"; } else { print HEX_OUT "$file"; print HEX_OUT " not match"; } } close(HEX_IN); close(HEX_OUT);
It has to be in hex string format. Thanks!

Replies are listed 'Best First'.
Re: Hex string search all files in directory
by LanX (Saint) on Dec 03, 2012 at 21:03 UTC
    I think you are overwriting the results for each file, "test.txt" is just the last one in the alphabet.

    What happens if you change

    open (HEX_OUT, ">>", $hex_out") or die "$!";

    to append instead of overwriting? Or even better you move it before the loop?

    Why don't you use warnings?

    BTW: proper indentation would facilitate reading your code =)

    Cheers Rolf

    PS:why do you escape the h in /\hello/?

Re: Hex string search all files in directory
by bdalzell (Sexton) on Dec 03, 2012 at 21:22 UTC
    if you want to match all instances of "hello" wether it is "HELLO","Hello" or "hello" you should also change the line:
    if ($hex_string =~ /\hello/)
    to:
    if (lc($hex_string)) =~ /\hello/)
      The more cannonical would be, in my opinion,
      if ($hex_string =~ /hello/i)
      لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ