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

hi monks

Can anyone tell me how to get the email in the var $found rather than just a true/false value, in the code below?
#!/usr/bin/perl use strict; use warnings; use Email::Find; my $text = "this is some text test\@email.com foo bar"; my $finder = Email::Find->new(\&find_email); my ($found) = $finder->find(\$text); print "Found says $found\n"; exit; sub find_email { my ($email, $orig_email) = @_; print "sub says " , $email->format(), "\n";; return $email->format(); } # end-sub
cheers,
reagen

Replies are listed 'Best First'.
Re: Email::Find question
by graff (Chancellor) on Mar 12, 2007 at 06:01 UTC
    Email::Find has, I think, a curious design. The text returned by the callback function is used to modify the contents of the original input text passed to the "find()" method, and "find()" itself simply returns "true" or "false" (1 or 0) for success or failure.

    The easiest way to get what you want (but perhaps not satisfactory in terms of OO/modular design) would be to use an array that is "global" to the main caller and callback function:

    #!/usr/bin/perl use strict; use warnings; use Email::Find; my $text = "this is some text test\@email.com foo bar"; my @found; my $finder = Email::Find->new( \&find_email ); $finder->find(\$text); print "Found says @found\n"; exit; sub find_email { my ( $email, $orig_email ) = @_; my $ret = $email->format(); print "sub says " ,$ret, "\n"; push @found, $ret; return; } # end-sub
    (Note that by returning undef, the callback will be removing email addresses from the original text string as they are processed.)

      The same, wrapped up in a convenient function:

      #!/usr/bin/perl use strict; use warnings; use Email::Find qw( ); sub extract_emails { my @emails; Email::Find->new(sub { my ($email, $orig_email) = @_; push @emails, $email->format(); return $orig_email; })->find(\$_[0]); return @emails; } my $text = "this is some text test\@email.com foo bar"; my @found = extract_emails($text);
Re: Email::Find question
by Khen1950fx (Canon) on Mar 13, 2007 at 07:45 UTC
    Personally, I like this module. I'm looking forward to some one updating it to RFC 2822, but I did manage to come up with this:

    #!/usr/bin/perl use strict; use warnings; use Email::Find; my $text = "this is some text test\@email.com foo bar"; my $finder = Email::Find->new(sub { my($email, $orig_email) = @_; print "sub says ".$email->format."\ +n"; print "Found says ".$email->format. +"\n"; return $orig_email; }); $finder->find(\$text);