Replace scalar in another scalar

M

Mark

Hello,

I have 2 scalars. I want to remove all occurences of one within the other.

I've tried this:

$delim = '|';
$value = "||||||||T||||||e||||||||||s|||||||||t||||||||!||||||";

$value =~ s/$delim//g;

print "$value\n";

.... but it doesn't work - it prints $value unaltered. What do I need to do
to the "$value =~ s/$delim//g;" line to realise that I'm reffering to the
_value_ of $delim, rather than the literal text "$delim"?

This is possibly a FAQ, but it's dead hard to know what to put into Go-Ogle
to find this information.

Thanks for any help,

Mark
 
A

A. Sinan Unur

Hello,

I have 2 scalars. I want to remove all occurences of one within the
other.

I've tried this:

$delim = '|';
$value = "||||||||T||||||e||||||||||s|||||||||t||||||||!||||||";

$value =~ s/$delim//g;

print "$value\n";

... but it doesn't work - it prints $value unaltered. What do I need
to do to the "$value =~ s/$delim//g;" line to realise that I'm
reffering to the _value_ of $delim, rather than the literal text
"$delim"?

Oh, but that is not what is happening. Indeed Perl is correctly using the
value of $delim. The problem is that the pipe character has a specific
meaning in regular expressions. Try:

#! /usr/bin/perl

use strict;
use warnings;

my $delim = '|';
my $value = "||||||||T||||||e||||||||||s|||||||||t||||||||!||||||";

$value =~ s/\Q$delim\E//g;

print "$value\n";
__END__

C:\Dload> q
Test!

For more information, read

perldoc perlretut

"Grouping things and hierarchical matching"

and

"More on characters, strings, and character classes"

Sinan
 
S

Sherm Pendley

Mark said:
I've tried this:

$delim = '|';
$value = "||||||||T||||||e||||||||||s|||||||||t||||||||!||||||";

$value =~ s/$delim//g;

print "$value\n";

... but it doesn't work - it prints $value unaltered. What do I need to do
to the "$value =~ s/$delim//g;" line to realise that I'm reffering to the
_value_ of $delim, rather than the literal text "$delim"?

You *are* getting the value of $delim. However, that value is a character
that has special meaning when used in regexes. You'd get the same result
from using the value as literal text:

$value =~ s/|//g;

To match a literal |, you need to escape it:

$value =~ s/\|//g;

So naturally, what you want to do is store the escape in $delim:

$delim = '\|';

sherm--
 
A

Arndt Jonasson

Martin Kissner said:
Mark wrote :

use strict;
use warnings;


$delim = '\|';

To let Perl help you get from '|' to '\|', you can use the quotemeta()
function:

$delim = '|';
$delim = quotemeta $delim;
 

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,733
Messages
2,569,439
Members
44,829
Latest member
PIXThurman

Latest Threads

Top