How to convert between a string w/ backslashes and a string w/special characters?

P

Peng Yu

Suppose I have a string $x='\t\n', I want to convert it to $y="\t\n".
I also want to convert $y back to $x. I have googled. But I haven''t
any related function, maybe because I didn't use the right search
keywords. Would you please let me know what functions I can use to do
the conversions?
 
P

Peter J. Holzer

--------------------
#!/usr/bin/perl
use warnings;
use strict;

$_ = q($x='\t\n');
tr/x'/y"/;
print "$_\n";
--------------------

From the posting guidelines:

| Speak Perl rather than English, when possible
| Perl is much more precise than natural language. Saying it in Perl
| instead will avoid misunderstanding your question or problem.
|
| Do not say: I have variable with "foo\tbar" in it.
|
| Instead say: I have $var = "foo\tbar", or I have $var = 'foo\tbar',
| or I have $var = <DATA> (and show the data line).

I think Yu was folling your advice here.

hp
 
S

sln

--------------------
#!/usr/bin/perl
use warnings;
use strict;

$_ = q($x='\t\n');
tr/x'/y"/;
print "$_\n";
--------------------

He has a string, it has a known value, its a constant.
Any conversion can't be treated programatically if the
new value is known and constant. Therefore, transliterate
is overkill, conceptually wrong, and slow.

The only answer is:

$string = q($x='\t\n');
$string = q($y="\t\n");

-sln
 
C

C.DeRykus

Suppose I have a string $x='\t\n', I want to convert it to $y="\t\n".
I also want to convert $y back to $x. I have googled. But I haven''t
any related function, maybe because I didn't use the right search
keywords. Would you please let me know what functions I can use to do
the conversions?

eval qq{\$y = "$x"; 1} or die $@;

But, I wouldn't necessarily recommend this.
String eval is slow and needs safeguards if
there's user input. See perldoc -f eval and
perldoc perlsec
 

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,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top