[Purdue-pm] Perl 5 exercise

Mark Senn mark at ecn.purdue.edu
Tue Nov 18 10:43:00 PST 2014


> The first half of this exercise shows the results of the computation.
> In the second half of the exercise replace "THIS" with ten characters
> that more clearly expresses the code in the first half of the
> exercise.
> 
> 
> #!/usr/new/bin/perl
> 
> my $line = 'Al <adam at a.com>, Bob B. Bob <bob at e.gov>, Bono <bono at u2.com>';
> 
> 
> $_ = $line;
> s/^.+?<//;
> s/>$//;
> my @email = split />.+?</;
> 
> print "first try\n";
> map  { print "($_)\n" }  @email;
> 
> 
> $_ = $line;
> # Replace THIS with ten characters that will produce the same answer as
> # above, and in my opinion more clearly expresses what you're trying to do.
> @email = THIS;
> 
> print "second try\n";
> map  { print "($_)\n" }  @email;

Running this program
    #!/usr/new/bin/perl
    my $_ = 'Al <adam at a.com>, Bob B. Bob <bob at e.gov>, Bono <bono at u2.com>';
    my @email = /<(.+?)>/g;
    map  { print "($_)\n" }  @email;
prints
    (adam at a.com)
    (bob at e.gov)
    (bono at u2.com)

The
     /<(.+?)>/g
dissected a character at a time:
    /    start matching (use, for example, "m/" in Perl 6)
    <    match a "<" verbatim
    (    start remembering what matched
    .    match any character
    +    one or more times
    ?    don't do greedy matching,
         only match up to the next ">", not to the last ">"
    )    stop remembering what matched
    /    end matching
    g    do the match globally so we get all the emai addresses

-mark


More information about the Purdue-pm mailing list