w3b has asked for the wisdom of the Perl Monks concerning the following question:

I wrote a script that checks how many emails we have on our account and then, when we write id(number), the script will write the subject of this email.
#!/usr/bin/perl use warnings; use strict; use Net::POP3; my $time = scalar localtime; my $pop3 = "pop3.poczta.onet.pl"; my $login = "haptor\@op.pl"; my $pass = "*************"; my $pop = Net::POP3->new($pop3); my $res = $pop->login($login, $pass); if ($res eq "undef"){ print "Couldn't connect $!\n"; exit; } else { print "On $time e-mail status inbox: $res post \n"; } print "Write id(number) email to read:\n"; chomp(my $msgnum = <STDIN>); my $msg = $pop->get($msgnum); if($msg =~ /Subject:(.*)From:/){ #I think that there is a error here print "Subject is $1"; } $pop->quit();
I want to extract the subject from the e-mail but $1 is empty.... I don't know what i do wrong... Maybe Regexp or bad variable.

Replies are listed 'Best First'.
Re: Problem with $1
by xdg (Monsignor) on Dec 03, 2005 at 14:40 UTC

    Read the docs for Net::POP3. get returns a reference to an array of lines, not the whole message.

    get ( MSGNUM [, FH ] ) Get the message MSGNUM from the remote mailbox. If FH is not given + then get returns a reference to an array which contains the lines of + text read from the server. If FH is given then the lines returned fr +om the server are printed to the filehandle FH.

    You just need to search through those lines for the subject.

    my $msg = $pop->get($msgnum); for my $line ( @$msg ) { if( $line =~ /^Subject:(.*)/ ) { print "Subject is $1"; last; } }

    Or, similarly, use print grep { /^Subject:/ } @$msg;

    Update: I should add that when I first read the subject "Problem with $1", my first thought was, "It's not $1,000,000?"

    Update: grep doesn't terminate after the first match. List::Util and first is better.

    -xdg

    Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.

      Ok!now it's good... thank you very very much... now i can think about add next functions;) Thank you one more time!

        Hi,

        I would also use my ($subject) = $line =~ ...
        It's cleaner than making the person examine the regex...

        Regards,

        fmerges at irc.freenode.net
Re: Problem with $1
by mulander (Monk) on Dec 03, 2005 at 14:36 UTC
    Try changing your regular expression to:
    /Subject:(.*)/
    ( ) does gruping and I think that was what you really wanted.
    I would also suggest that you look on cpan and see if you can find a good mail heade parser, I am almost 100% sure that you will find it done ;) Do not reinvent the whell.
      no:( $1 is further empty:/ maybe my source code is bad, but when i run scripts with -c i see "syntax OK" - so what?I don't know what i do wrong:/