Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: Arrays and grep problems

by Kenosis (Priest)
on Jan 24, 2014 at 19:43 UTC ( [id://1071986]=note: print w/replies, xml ) Need Help??


in reply to lolhackedlol

You've been given excellent tips for improving your script. In an earlier response to you, Laurent_R suggested two methods for accomplishing your task. The following addresses one of those, as I think it's a good option.

When you're looking for keywords in each line, you're effectively joining them with OR. For example: print the current file's line if it contains 'Hello' OR 'world' OR 'today'. In a regex, the OR function is accomplished using alternation:

/(?:Hello|world|today)/

The (?:) notation forms a non-capturing group. It's not strictly necessary here, but is used to just cluster the set of disjuncts.

There are a few issues with the above regex which need to be addressed. One is that, as it is, it's case sensitive. That is, 'today' would match but 'Today' wouldn't. To create a case-insensitive match, use the i modifier:

/(?:Hello|world|today)/i

The next issue is that the above regex would match 'worldly'--and you may not want in-string matching. To prevent in-string matching, you need to match words enclosed by word boundaries:

/(?:\bHello\b|\bworld\b|\btoday\b)/i

The last item to consider comes when you may want to match a phrase like 'Mr. Smith'. The problem is that the period in the string is a regex meta-character used to match one character. This period, and other meta-characters, must be escaped for a literal match: 'Mr\. Smith'.

Give the above considerations, the script below implements them:

use strict; use warnings; use autodie; my @arr; my $logz = '/var/log/syslog'; my $file = '/home/user/Desktop/keywords'; open my $keysFH, '<', $file; while (<$keysFH>) { chomp; push @arr, "\\b\Q$_\E\\b"; } close $keysFH; my $words = '(?:' . ( join '|', @arr ) . ')'; my $regex = qr/$words/i; open my $logFH, '<', $logz; while (<$logFH>) { print if /$regex/; } close $logFH;

The "\\b\Q$_\E\\b" notation first quotes all meta-characters in the word (\Q...\E) and the \\b means word boundary. There are two "\", because the first escapes the second, leaving the literal "\b" in the string.

Print both $words and $regex to see what's constructed.

Usage: perl script.pl [>outFile]

The last, optional parameter directs output to a file.

Hope this helps!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1071986]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (4)
As of 2024-03-29 07:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found