简体   繁体   English

perl替换字符串中的字符,但保留特殊字符或空格

[英]perl replace characters in a string but retain special character or space

I would like to create a program that replaces characters and retains the special characters. 我想创建一个替换字符并保留特殊字符的程序。 An example input and output is shown below. 输入和输出示例如下所示。

Here's what I did so far: 这是我到目前为止所做的:

$sentence = userinput;

@words = split(/ /, $sentence);

for ($i = 0; $i < @words.length; $i ++){
    $words[$i] =~ s/\W//g;
    @characters = split(//, $words[$i]);
    #print $words[$i] . "\n";

    $wordlength = length($words[$i]);


    for ($j = 0; $j < @characters.length; $j ++){

    $char = $characters[$j];

    for ($x = 0; $x < $wordlength; $x++){
        $char++;
        if ($char eq "aa"){
            $char = "a";
        }
        elsif ($char eq "AA"){
            $char = "A";
        }
    }
    print $char;
    if ($x = 0){
        $output[$i] = $char;
    }
    else {
        $output[$i] = join ($char);
    }
}

print $output[$i];
}

Input: 输入:

Hi! 嗨! how are you doing? 你好吗?

Output: 输出:

Jk! k! krz duh brx itnsl? krz duh brx itnsl?

A couple of things in your code don't make sense: 代码中的几件事没有意义:

  • Missing use strict; use warnings; 缺少use strict; use warnings; use strict; use warnings; .
  • All variables are global (you should be using my to create variables) 所有变量都是全局变量(您应该使用my来创建变量)
  • @foo.length is not the number of elements in the array @foo . @foo.length不是数组@foo的元素数。 It's the number of elements in the array @foo concatenated with the number of characters in $_ (because arrays in scalar context return their length, . concatenates strings, and length works on $_ by default). 它是@foo数组中的元素数与$_的字符数串联在一起(因为标量上下文中的数组返回其长度, .连接字符串,并且默认情况下length$_上起作用)。
  • join ($char) always returns the empty string: You're joining an empty list (no elements) using $char as a separator. join ($char)始终返回空字符串:您正在使用$char作为分隔符来连接一个空列表(无元素)。

Here's an attempt to fix all of these issues: 这是解决所有这些问题的尝试:

use strict;
use warnings;

my $sentence = readline;

$sentence =~ s{([A-Za-z]+)}{
    my $word = $1;
    join '', map {
        my $base = ord(/^[A-Z]/ ? 'A' : 'a');
        chr((ord($_) - $base + length($word)) % 26 + $base)
    } split //, $word
}eg;

print $sentence;

I think what you are doing is rot3 encoding, but if so then your example is wrong 认为您正在执行的是ro​​t3编码,但是如果是这样,那么您的示例是错误的

my $sentence = 'Hi! how are you doing?';
$sentence =~ tr/A-Za-z/D-ZA-Cd-za-c/;
print $sentence, "\n";

output 输出

Kl! krz duh brx grlqj?

which is similar, but not identical to 相似但不相同

Jk! krz duh brx itnsl?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM