Parsing Perl.. Please explain..

  • Thread starter Oldbitcollector
  • Start date
O

Oldbitcollector

I've got a routine that looks something like this...

for( $i = 1; $i <= $pop->Count(); $i++ ) {
foreach( $pop->Head( $i ) ) {
/^(From|Subject):\s+/i && print $_, "\n";
}
}

This parses two lines from an email header. (From & Subject)

I'm having some trouble understanding how this works.
I'm shooting for a parse that would put this lines into variables as
well as print them.

something like

$from = /^(From):\s+/i
print $from;

$subject = /^(Subject):\s+/i
print $subject;

Could someone take a little time to explain how this works so I can
apply it correctly to my own code requirements. Thanks

Jeff
 
T

Tad McClellan

I've got a routine that looks something like this...

for( $i = 1; $i <= $pop->Count(); $i++ ) {


foreach my $i ( 1 .. $pop->Count() ) {

foreach( $pop->Head( $i ) ) {
/^(From|Subject):\s+/i && print $_, "\n";
}
}

This parses two lines from an email header. (From & Subject)

I'm having some trouble understanding how this works.


When you have things "and"ed together, as soon as you encounter
a false value, you can stop evaluating clauses because you already
know that the whole expression must be false.

Perl takes that same short cut.

When the m// is false, the print() is never evaluated.

The print() is evaluated only when the m// is true.

The body of the for loop is equivalent to:

if ( /^(From|Subject):\s+/i ) {
print $_, "\n";
}

I'm shooting for a parse that would put this lines into variables as
well as print them.


if ( /^(From|Subject):\s+/i ) {
print $_, "\n";
$hash{$1} = $_;
}
 
J

Joe Smith

Oldbitcollector said:
something like

$from = /^(From):\s+/i
print $from;

$subject = /^(Subject):\s+/i
print $subject;

my($from,$subject);
while(...) {
/^From:\s+/i and $from = $_;
/^Subject:\s+/i and $subject = $_;
}
print $from if defined $from;
print $subject if defined $subject;

A better way would be to use a hash instead of separate values.
You can use

/^(From|Subject):\s/i and $requested_headers{lc $1} = $_;

or

$requested_headers{lc $1} = $_ if /^(From|Subject):\s/i;

to do that.

Both statements do the same thing; it's a matter of style whether you prefer
(condition) and $variable = $value;
versus
$variable = $value if (condition);

-Joe
 
O

Oldbitcollector

Thanks guys,

With that explaination and a couple more hours of study, I'm starting
to understand how this works.


Jeff
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top