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:
<kamil@yahoo.com>
From: "=?iso-8859-9?B?RXYgVGH+/W1hY/1s/fD9bmRhIsdfyhjdbmRRmltIFNlem9u?=
=?iso-8859-9?B?dQ==?=" <kamil@yahoo.com>
my code prints 2 lines for this file:
kamil@yahoo.com
kamil@yahoo.com
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 {
开发者_Go百科$line = <FILE>;
if ( $line =~ m/.*<(.*)>.*/ ) {
$from = $1;
}
}
print $from . "\n";
}
}
thanks in advance.
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:
<kamil@yahoo.com>
From: "=?iso-8859-9?B?RXYgVGH+/W1hY/1s/fD9bmRhIsdfyhjdbmRRmltIFNlem9u?=
=?iso-8859-9?B?dQ==?=" <kamil@yahoo.com>
精彩评论