Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

using tr///

Status
Not open for further replies.

k1ng0fn3rd

Programmer
Aug 6, 2006
17
US
How come this code:
Code:
$text = "abcdefghijklmnopqrstuvwxyz";
$text =~ tr/a-z/1-{26}/;
print "$text\n";
produces this output:
123456789:;<=>?@ABCDEFGHIJ
?

--------------------------
The best answer to your question will definitely be RTFM.
 
I'm pretty sure it's just the 1-{ that is being evaluated in the replacement list:

$text =~ tr/a-z/1-{/;

evidently perl is interpreting 1-{ as the range of characters you are getting as the results:

123456789:;<=>?@ABCDEFGHIJ

personaly I would have thought perl would see that as an invalid range and echo a warning or error message. You can't use tr/// to try and translate a-z into 1-26 if that is what you are trying to do.
 
Yes, tr/// does single-character transliteration, so trying to replace 'z' with '26' doesn't make sense, since 26 is two characters.
 
yes, but why is 1-{ not generating a warning or error?

Invalid range [] blah blah blah....
 
AFAIK, the invalid range error is only if the second character is smaller (i.e. has a smaller ascii code) than the first, so 1-0 gives the error, for example.
 
alright, that makes sense. is there anyway to do this with tr///, or would you have to do something like this:
Code:
@abc = 'a','b','c';
%alpha = ( 'a' => 1,
           'b' => 2, #etc...
                    );
foreach $letter (@abc)
{
       $num =~ s/$letter/$alpha{$letter}/;
       push(@abc,$num);
}

--------------------------
The best answer to your question will definitely be RTFM.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top