smknjoe has asked for the wisdom of the Perl Monks concerning the following question:
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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Evaluating variables within a string
by NetWallah (Canon) on Dec 06, 2017 at 00:26 UTC | |
|
Re: Evaluating variables within a string
by nysus (Parson) on Dec 06, 2017 at 00:27 UTC | |
|
Re: Evaluating variables within a string
by AnomalousMonk (Archbishop) on Dec 06, 2017 at 00:58 UTC | |
by smknjoe (Beadle) on Dec 06, 2017 at 16:08 UTC | |
|
Re: Evaluating variables within a string
by Dallaylaen (Chaplain) on Dec 06, 2017 at 05:14 UTC |