Operating System - Linux
1753796 Members
7317 Online
108799 Solutions
New Discussion юеВ

Re: PERL - Escape special characters

 
Anand_30
Regular Advisor

PERL - Escape special characters

Hi,

I have a PERL script which reads inputs from another file. But each line in the input has few special characters which needs to be escaped.

Can anyone tell me the best way to do this?

Is there any package available in PERL which when used automatically escapes special characters.

Thanks,
Anand
4 REPLIES 4
James R. Ferguson
Acclaimed Contributor

Re: PERL - Escape special characters

Hi:

I would read the file in raw (binary) mode:

#/usr/bin/perl
my $/ = "\0";
while (<>) {
...
}

Regards!

...JRF...
Oviwan
Honored Contributor

Re: PERL - Escape special characters

Hi

#!/usr/bin/perl
while (<>)
{
chomp;
#Put all special characters in the search pattern
$_ =~ s/([\$\#\@\\])/\\$1/g;
print "$_\n";
}

Regards
H.Merijn Brand (procura
Honored Contributor

Re: PERL - Escape special characters

JRF, that is NOT raw mode.

method 1

open my $file, "< $file_name" or die "$file_name: $!";
binmode $file;

method 2

open my $file, "<:raw", $file_name or die "$file_name: $!";

What you probably MEANT was

local $/; # set's input record separator to undef
my $content = <>; # 'while' is useless

Being escaped is a too wide and unspecific defenition to give a solution for

# insert a backslash in fron of specials
s{([.....])}{\\$1}g;

where ..... is the range of characters that need the \

but you could also mean to `escape' characters to html entities or octal escapes or ...

Enjoy, Have FUN! H.Merijn
Enjoy, Have FUN! H.Merijn
James R. Ferguson
Acclaimed Contributor

Re: PERL - Escape special characters

Hi Merijn!

Yes, method-2 as you described where was I was (badly) trying to get toward :-)

/* no points please */

Regards (and thanks)!

...JRF...