kursat
kursat

Reputation: 1099

How to check if string matches a regular expression in perl?

i have a problem with perl. i want to parse an email object or log or file whatever. i want to find where is mail comes from. first i have to check "x-envelop-from" line, if there isn't match, then i have to check "from" line.

this is some of my sample file:

X-Envelope-From: 
    <[email protected]>
From: "=?iso-8859-9?B?RXYgVGH+/W1hY/1s/fD9bmRhIsdfyhjdbmRRmltIFNlem9u?=
    =?iso-8859-9?B?dQ==?=" <[email protected]>

my code prints 2 lines for this file:

[email protected]
[email protected]

hoe can be possible, both print lines are printed in if and elsif? is there a problem at checking matches?

while ( $line = <FILE>) 
{
    my ($from, $to, $spam_id, $date, $tmp_date, $m_day, $m_mon, $m_year, $m_hour, $m_min, $pos_tmp);
    my ($subject);
# 
    if ( $line =~ m/^(X-Envelope-From:).*/ ) {
        if ( $line =~ m/^X-Envelope-From:.*<(.*)>.*/ ) {
            $from = $1;
        }
        else {
            $line = <FILE>;
            if ( $line =~ m/.*<(.*)>.*/ ) {
                $from = $1;
            }
        }
        print $from . "\n";
    }

    elsif ( $line =~ m/^(From:).*/ ) {
        if ( $line =~ m/^From:.*<(.*)>.*/ ) {
            $from = $1;
        }
        else {
            $line = <FILE>;
            if ( $line =~ m/.*<(.*)>.*/ ) {
                $from = $1;
            }
        }
        print $from . "\n";
    }
}

thanks in advance.

Upvotes: 0

Views: 2141

Answers (1)

Alan Haggai Alavi
Alan Haggai Alavi

Reputation: 74292

Use a specialised module such as Email::MIME to parse the headers:

#!/usr/bin/env perl

use strict;
use warnings;

use Email::MIME;

my $em = Email::MIME->new(
    do { local $/; <DATA> }
);

my $from = $em->header('X-Envelope-From');
$from = $em->header('From') unless $from;

$from =~ s{.*<|>.*}{}g;
print $from;

__DATA__
X-Envelope-From: 
    <[email protected]>
From: "=?iso-8859-9?B?RXYgVGH+/W1hY/1s/fD9bmRhIsdfyhjdbmRRmltIFNlem9u?=
    =?iso-8859-9?B?dQ==?=" <[email protected]>

Upvotes: 6

Related Questions