Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
use strict; use warnings; my $combined = ''; my ( $a, $b, $c ) = ( 1, 0, 1 ); eval qq(if ( \$$_ ) { \$combined .= "$_=\$$_ " }) for qw( a b c ); print "$combined\n"; __END__ a=1 c=1

Update: Quotation bug fixed. (In the original version of my solution the RHS of the concat/assignment in the eval was the single-quoted '$_=\$$_ ', resulting in $combined ending up with the value 'a=$a c=$c' instead of 'a=1 c=1').

Also, to clarify what the eval is doing, at each iteration, only the $_ get interpolated; the remaining $'s are quoted verbatim. Hence, in the first iteration, the argument to eval is the string

'if ( $a ) { $combined .= "a=$a " }'
All the a's in this string come from interpolating $_, whereas the $'s come from the \$'s in the original double-quoted expression.

The fuss with double quotes and backslashes is a way to selectively interpolate certain values (i.e. $_'s); without all the backslashing, perl would try to interpolate $$, for example.

Perhaps this is a clearer alternative:

my $template = 'if ( $%s ) { $combined .= "%s=$%s " }'; eval sprintf $template, $_, $_, $_ for qw( a b c );
Of course, in the last snippet, $template can alternatively be set to
'$combined .= "%s=$%s " if $%s'
or
'$%s and $combined .= "%s=$%s "'

the lowliest monk


In reply to Re: Scalar joining, concatenation, involving varying text by tlm
in thread Scalar joining, concatenation, involving varying text by mhearse

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (7)
As of 2024-04-24 10:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found