Replace substring "_.modem_" with modem price from $price ?

M

Martina

How to replace (change) some pattern in array with value of variable.
Replace substring "_.modem_" with modem price from $price

----------------------
@fileList=("Price for new modem is: _modem_?.", "Modem is price is:
_modem_?.");
$price=10;

foreach $red(@fileList){@rast = split ("_modem_",$red);
if ($#rast > 0) {
print "$rast[0]$price$rast[1]\n";
}
}
 
A

Anno Siegel

Martina said:
How to replace (change) some pattern in array with value of variable.
Replace substring "_.modem_" with modem price from $price

Please use warnings and strict in your code. In consequence, you'll
have to declare your variables. Also your code would profit from
some white space.

Your code doesn't change anything, it only prints the changed strings.

Is @fileList an appropriate name? The elements don't look like plausible
file names.
$price=10;

foreach $red(@fileList){@rast = split ("_modem_",$red);

The first argument of split() is a regex, it should be written as such:

... split /_modem_/, $red;
if ($#rast > 0) {
print "$rast[0]$price$rast[1]\n";

Since you already have the pieces in a list you can put them together
with join();

print join( $price, @rast), "\n";

If your problem description is correct, you don't have a solution yet.

The normal way in Perl to change parts of a string is a substitution
s///. This changes the elements of @fileList according to your
description:

my @fileList = (
'Price for new modem is: _modem_?.',
'Modem is price is: _modem_?.',
);
my $price = 10;

s/_modem_/$price/ for @fileList;

print "$_\n" for @fileList;

Anno
 
A

Anno Siegel

David Serrano (Hue-Bond) said:
Anno Siegel, vie20050909@11:01:39(CEST):

Just a note. I think walking the array only once would be better
performance-wise, wouldn't it?

It might. Only a benchmark would tell. In combination with actual IO
the difference isn't going to be large.

I set the print statement it off in an extra loop because it is only there
to show that the rest of the program worked. It shows an intent, efficiency
wasn't on my mind.
for (@fileList) {
s/_modem_/$price/;
print "$_\n";
}

Or, shorter;

s/_modem_/$price/, print "$_\n" for @fileList;

Yes, but it combines two actions one of which is likely to go away
in a finished program.

Anno
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,565
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top