考虑一个包含以下内容的文本文件:
apple apple pear plum apple cherry pear apple
cherry plum plum pear apple cherry pear pear apple plum
Run Code Online (Sandbox Code Playgroud)
并考虑perl one-liner:
perl -pe "s/apple/green/g and s/pear/yellow/g and s/plum/blue/g and s/cherry/red/g" < fruits.txt
Run Code Online (Sandbox Code Playgroud)
这取代了每种水果的颜色.
现在,这可以用一个s /// g以某种方式完成,而不是上面的四个吗?
我也关注水果词的顺序.
如果我的样本不包含"apple",则其他替换都不会完成.我该怎么解决这个问题?
请注意:我希望将解决方案保持为单行.
因此,定义哈希,读取文件以及需要多行perl代码的其他解决方案并不能让我前进.
这更像是一种好奇心,而不是一个项目所依赖的生死攸关的问题.现在困扰我好几天了,并且认为一个更有经验的perl用户可以帮助解决心跳,或者让我摆脱困境,直接告诉我这不可能按照我想要的方式完成.