
methods to insert/substitute blocks of text?
...
Quote:
> In case anyone wants
> to explain a little, I've put my questions below... I'm a novice, so be
> patient. ;)
...
Well, since you asked so nicely...
Quote:
...
> > sub template {
> ---
> anyone explain?
This statement assigns a list to a list, which is done scalar by scalar.
The first argument $_[0] is assigned to $filename; the second argument
$_[1] is assigned to $fillings.
Quote:
> > my $text;
> > local $/; # slurp mode (undef)
> ---
> what's this? any suggested reading? i.e. why do we need to worry about
> the input record separator, or is that not what it is here?
Yes, it is, and we don't want no s{*filter*}keen' input record separator (in
order to handle parameter substitutions that span more than one line).
See the discussion of $/ in perlvar.
Quote:
> > local *F; # create local filehandle
> > open(F, "< $filename") || return;
> > $text = <F>; # read whole file
> > close(F); # ignore retval
> ---
> whups, I got lost here... doesn't reading the the whole file into a
> string "lose" the line returns... how will we get them back?
No, they're still there. Each one is in the string as the single
character "\n", regardless of their external representation.
Quote:
> > # replace quoted words with value in %$fillings hash
> > $text =~ s{ %% ( .*? ) %% }
> > { exists( $fillings->{$1} )
> > ? $fillings->{$1}
> > : ""
> > }gsex;
> ---
> can someone go slow and explain what each line of this expression does?
Extract into $1 the fewest number of characters between pairs of '%%' and
'%%' (including none; the * could as well have been a +). If that string
is a key of the hash referred to by $fillings, replace the matched string
by the value of the hash member; otherwise replace the matched string by
nothing. [Even more compactly: { exists $fillings->{$1} && $fillings-
Quote:
>{$1} } .]
Do it over and over ('g'), allowing the '.' to match the embedded "\n"
characters ('s'), evaluating the second part of the substitution as a
Perl expression ('e'), and allowing for white space and comments in the
regular expression ('x'). [The order of these four options is
irrelevant. Hmmm...]
Quote:
> > return $text;
> > }
> ---
> ok, I see that this returns the now-substituted text, and I'm assuming
> that since the \n weren't chomped out when the file was read into $text,
> that they pop back out when returned. correct?
No, they were there all along.
All this is somewhat beyond 'Learning Perl' but certainly clear enough
from 'Programming Perl' or perlre.
--
Larry Rosler
Hewlett-Packard Laboratories
http://www.*-*-*.com/