Multiple s/xx/yy/

U

Ulrich Herbst

Hi,

I have to substitute multiple patterns in a template with different
values.

Something like that:

----------------------------------------------------------------------
#!/usr/bin/perl

use strict;
use warnings;

my $template='a##1b##2c##3';

my $var1='x';
my $var2='y';
my $var3='z';

(my $newvar = $template) =~ s/##1/$var1/g;
$newvar =~ s/##2/$var2/g;
$newvar =~ s/##3/$var3/g;

print $newvar ."\n";
# $newvar = 'axbycz'
----------------------------------------------------------------------

Can I put these three lines with "s/.../.../" in one line ?

Uli

--
'''
(0 0)
+------oOO----(_)--------------+
| |
| Ulrich Herbst |
| |
+-------------------oOO--------+
|__|__|
|| ||
ooO Ooo
 
P

Paul Lalli

Ulrich said:
Hi,

I have to substitute multiple patterns in a template with different
values.

Something like that:

----------------------------------------------------------------------
#!/usr/bin/perl

use strict;
use warnings;

my $template='a##1b##2c##3';

my $var1='x';
my $var2='y';
my $var3='z';

(my $newvar = $template) =~ s/##1/$var1/g;
$newvar =~ s/##2/$var2/g;
$newvar =~ s/##3/$var3/g;

print $newvar ."\n";
# $newvar = 'axbycz'

You might be better off using a hash instead of three separate variables:
my %replace = (1=>'x', 2=>'y', 3=>'z');

(my $newvar = $template) =~ s/##(\d)/$replace{$1}/g;

Paul Lalli
 
G

Gregory Toomey

Ulrich said:
Hi,

I have to substitute multiple patterns in a template with different
values.

Something like that:

----------------------------------------------------------------------
#!/usr/bin/perl

use strict;
use warnings;

my $template='a##1b##2c##3';

my $var1='x';
my $var2='y';
my $var3='z';

(my $newvar = $template) =~ s/##1/$var1/g;
$newvar =~ s/##2/$var2/g;
$newvar =~ s/##3/$var3/g;

print $newvar ."\n";
# $newvar = 'axbycz'
----------------------------------------------------------------------

Can I put these three lines with "s/.../.../" in one line ?

Uli

You need 'apply':
http://gregorytoomey.com/index.php?option=content&task=view&id=15&Itemid=28


gtoomey
 
T

Tad McClellan

I have to substitute multiple patterns in a template with different
values.

my $var1='x';
my $var2='y';
my $var3='z';


my @vars = qw/ x y z /;

(my $newvar = $template) =~ s/##1/$var1/g;
$newvar =~ s/##2/$var2/g;
$newvar =~ s/##3/$var3/g;


(my $newvar = $template) =~ s/##(\d+)/$vars[$1-1]/g;
 

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

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,077
Latest member
SangMoor21

Latest Threads

Top