Simple Perl Regex Analyzer

Hey, I'm working on a very simple parser. I am pretty sure my regex is correct, but the values ​​do not seem to be stored in mine $1and $2. Am I doing something wrong? I'm just looking for tips on changing the code. Thanks for any advice! Also, I am new to Perl, so if I did something wrong, I am looking to get on the right foot and develop strong habits.

Example line from file:

Sat 02-August-2008 20:47 - 123.112.3.209 - "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1;

I just get hours from time to time.

foreach my $line (@lines)
{   
my $match =~ /\d\d-\w+-\d{4} (\d)(\d):\d\d/;

if( $1 == 0)
{
    $times[$2] = $times[$2] + 1;
}
else
{   
    my $time = $1.$2;
    $times[$time] = $times[$time]+ 1;
}
 }


print "\n";
for(my $i=0;$i<24;$i++)
{
print "$i: $times[$i]\n";
}
+3
source share
3 answers

If you want a match on $line, do not read the code

$line =~ /\d\d-\w+-\d{4} (\d)(\d):\d\d/;

See here .

+7
source

, ? , . , :

, , , $1, $2 ..

if($match =~ /\d\d-\w+-\d{4} (\d)(\d):\d\d/) {

    if( $1 == 0)
    {
        $times[$2] = $times[$2] + 1;
    }
    else
    {   
        my $time = $1.$2;
        $times[$time] = $times[$time]+ 1;
    }
} else {
    warn "no match!\n";
}

-, -w. , , $1 $2, - :

#!/usr/bin/perl -w
+3

-, Perl, CPAN . !

Date:: Parse, . , , .

Based on your single line sample, this code will do this:

use strict;
use warnings;

use Date::Parse;

my $line="Sat 02-August-2008 20:47 - 123.112.3.209 - \"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1;";
my $tmpart;

if ($line=~ /^(.*\d+:\d+) -/) {
    $tmpart=$1;

    print "Time part = $tmpart\n";

    my $time=str2time($tmpart);
    my ($ss,$mm,$hh,$day,$month,$year,$zone) = strptime($tmpart);

    $year+=1900;
    $month+=1;

    print "Unix time: $time\n";
    print "Parsed time: $month/$day/$year $hh:$mm:$ss  \n\n";
} 
else {
   warn "no match!\n";
}   

This will return a Unix time number that is easy to work with. Or (as shown) you can analyze the individual components of time.

+1
source

Source: https://habr.com/ru/post/1764429/


All Articles