Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: Here documents in blocks [s///r chaining]

by kcott (Archbishop)
on Dec 20, 2020 at 17:00 UTC ( [id://11125503]=note: print w/replies, xml ) Need Help??


in reply to Here documents in blocks

Me again. I don't think I've ever written this many responses to a single OP. :-)

Use of s///r has been mentioned in more than one post. I wondered if you knew that you could chain them. You can also chain y///r and mix them up. This type of extended construct is valid; although, I can't think of an immediate use for such a beast:

$str =~ s///r =~ y///r =~ s///r =~ tr///r

I saw where you'd written that you don't really have time to learn a completely new system. The following may be useful in its own right; however, it may get you halfway to writing a more formal template. When you do get around to looking at templating systems — and I do recommend you at least put that on your TODO list — you'll probably notice the similarities between placeholders like __TOKEN__ here and those used by templating systems, such as <% TOKEN %>.

In the following code, the main processing, including the s///r chaining, is all at the front; the (messy) heredocs are written as theredocs and moved out of the way to the end of the code.

$ perl -E ' my @users = ( { audience => "Management" }, { audience => "Employee" }, { audience => "Guest" }, ); generate_report($_) for @users; sub generate_report { my ($user) = @_; say main_template() =~ s/__AUDIENCE__/$user->{audience}/r =~ s/__MNGT_REP__/mngt_rep($user)/er =~ s/__EMP_REP__/emp_rep($user)/er =~ s/__GUEST_REP__/guest_rep($user)/er; } # Theredocs (out of the way) sub main_template { <<EOF <p> Report for __AUDIENCE__. </p> __MNGT_REP____EMP_REP____GUEST_REP__ EOF } sub mngt_rep { my ($viewer) = @_; return "" unless $viewer->{audience} eq "Management"; return <<EOF <div> ... Management Report ... </div> EOF } sub emp_rep { my ($viewer) = @_; return "" unless $viewer->{audience} eq "Employee"; return <<EOF <div> ... Employee Report ... </div> EOF } sub guest_rep { my ($viewer) = @_; return "" unless $viewer->{audience} eq "Guest"; return <<EOF <div> ... Guest Report ... </div> EOF } '

When run, that outputs:

<p> Report for Management. </p> <div> ... Management Report ... </div> <p> Report for Employee. </p> <div> ... Employee Report ... </div> <p> Report for Guest. </p> <div> ... Guest Report ... </div>

— Ken

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11125503]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (5)
As of 2024-04-18 11:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found