开发者

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

开发者 https://www.devze.com 2023-01-02 11:46 出处:网络
Perl code fragment: my $export = $doc; $export =~ 开发者_JAVA技巧s:\\.odt:\\.pdf:; How would this be written cleaner? Not simply what are 900 other ways to write it, TMTOWTDI. 

Perl code fragment:

my $export = $doc;
$export =~ 开发者_JAVA技巧s:\.odt:\.pdf:;

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


 

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};


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号