Hello,

I have the following code. It works and does what I pretty much want it to do, but it doesn't look the greatest. I was wondering if there is a better, cleaner approach to doing the same thing. Originally the $string had $i, but that errored out due to the fact that $i wasn't defined yet and because I needed it to be evaluated inside the for loop to expand it. Also, I was hoping to simply eval the string, but it isn't real Perl code so that wasn't a viable option.

#!/usr/bin/env perl use strict; use warnings; ### This eval code snippet works ### eval(my $ref2 = "parent_ref"); #################################### my $string = "first_string ref[i] second_string $ref2.ref[i] third_str +ing"; my $new_string; my $i; for ($i=0; $i<5; $i++) { print "$i : "; $new_string = $string; # don't clobber original string, else searc +h-and-replace fails after first loop $new_string =~ s/\[i\]/\[$i\]/g; print "$new_string\n"; }

And the output looks like this:

0 : first_string ref[0] second_string parent_ref.ref[0] third_string 1 : first_string ref[1] second_string parent_ref.ref[1] third_string 2 : first_string ref[2] second_string parent_ref.ref[2] third_string 3 : first_string ref[3] second_string parent_ref.ref[3] third_string 4 : first_string ref[4] second_string parent_ref.ref[4] third_string

Anyways, I'm just hoping there's a better way to possibly do this that is probably more advanced than my Perl skillset allows.

Thanks, Joe W.


In reply to Evaluating variables within a string by smknjoe

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



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.