Codeit1978
asked on
Perl hash
Hello, I have a perl script that grep though a log file and if the regular expression matches it add's it to the hash. It would appear that it's only adding the first instance to the hash.
What I would like to do is have it add the last found instance that matches the reg expression to the hash.
Can this be accomplished?
What I would like to do is have it add the last found instance that matches the reg expression to the hash.
Can this be accomplished?
ASKER
Hey, sorry, here is a snip of th elogs. So I have an if statement that if the reg expression meets add it to the hash. So as it, it only stores the first match, I would like it to ignor the first and only store the last.
my %user;
if(/\((\d+)\/(\d+)? (\d+):(\d+):(.*)\):\{.*\} \{(.*)/)
{
$user{full} = $6;
}
With what you've shown, it will update the hash every time it matches. So after looping through a file, it will store the last match - unless there is something in your loop going through the logs that causes it to stop processing. You'll have to post more of your code, and maybe a log.
ASKER
Let me test again to verify.
are there more than one matches on a single string?
a regex on a string will match at the first place it can in that string
to get the last match in a string you can do
/[.\n]*\((\d+)\/(\d+)? (\d+):(\d+):(.*)\):\{.*\} \{(.*)/
a regex on a string will match at the first place it can in that string
to get the last match in a string you can do
/[.\n]*\((\d+)\/(\d+)? (\d+):(\d+):(.*)\):\{.*\} \{(.*)/
Since none of your five matches is preceded by \} \{, you could perhaps leave out the beginning of the regex string and use only the end, e.g.
if ( /\} \{(.*)/ ) {
$user{full} = $1;
}
if ( /\} \{(.*)/ ) {
$user{full} = $1;
}
perhaps... unless there could be } { in
:(.*)\):
:(.*)\):
Yeah, that is true, then this could work
IF /(.*)\):\{.*\} \{(.*)/
... again unless a similar combination follows somewhere in the string.
The author should paste the string.
IF /(.*)\):\{.*\} \{(.*)/
... again unless a similar combination follows somewhere in the string.
The author should paste the string.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
For a hash, a given key can have only 1 value (this value can be a reference to an array that contains multiple values...). So if you want the last match, you could just set the hash with that key to the value. Any previous value will be thrown away, and the new value stored.