Cleanup Perl code: my $export = $doc; $export =~ s:\.odt:\.pdf:;

跟風遠走 提交于 2019-12-11 06:24:06

问题


Perl code fragment:

my $export = $doc;
$export =~ s:\.odt:\.pdf:;

How would this be written cleaner? Not simply what are 900 other ways to write it, TMTOWTDI.


回答1:


 

my ($export = $doc) =~ s{\.odt}{\.pdf};

UPDATE: That solution doesn't compile (note to self: test before posting on SO). Instead you could say

(my $export = $doc) =~ s{\.odt}{\.pdf};



回答2:


I go for [.] to match a literal period:

$export ~= s{[.]odt$}{.pdf};

Note that only the first half of the s/// call is a regular expression. The replacement is a normal string, and does not require a period to be escaped.

You might want to represent files as objects and not strings, though, with Path::Class.




回答3:


my %ext = ( 'odt' => 'pdf', etc... ); (my $export = $doc) =~ s{.([^.]+)$}{'.'.($ext{$1}||$1})}eg;



来源:https://stackoverflow.com/questions/2954432/cleanup-perl-code-my-export-doc-export-s-odt-pdf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!