bcc32
bcc32

Reputation: 328

Perl Rot47 with tr///?

I have the following code:

#!/usr/bin/env perl

for ($str = <>; $str != '`'; $str = <>) {
    $str =~ tr/!-~/P-~!-O/;
    print $str;
}

but the ROT47 doesn't work properly. i.e.
It quits when I start $str with a character not in [1-9] (Yes that means 0 doesn't work).

Upvotes: 1

Views: 450

Answers (1)

ephemient
ephemient

Reputation: 204926

$str != '`'

is a numeric comparison. Both "0\n" and "`" (as well as any string not starting with a decimal digit or point) are numerically zero, so they are equal.

You meant to use the string comparison ne.

(Also, always use strict; and use warnings;; the latter would have caught this error.)

A more typical way to write this would be

while (my $str = <>) {
    last if $str =~ /^`$/;
    $str =~ tr/!-~/P-~!-O/;
    print $str;
}

Upvotes: 8

Related Questions