perl – 使用@_中元素的引用来避免重复代码

前端之家收集整理的这篇文章主要介绍了perl – 使用@_中元素的引用来避免重复代码前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在子程序中引用@_的元素以避免重复代码是否安全?我也想知道以下是好的做法还是可以简化.我有一个子程序mod_str,它接受一个选项,说明是否应该就地修改字符串参数:
  1. use feature qw(say);
  2. use strict;
  3. use warnings;
  4.  
  5. my $str = 'abc';
  6.  
  7. my $mstr = mod_str( $str,in_place => 0 );
  8. say $mstr;
  9. mod_str( $str,in_place => 1 );
  10. say $str;
  11.  
  12. sub mod_str {
  13. my %opt;
  14. %opt = @_[1..$#_];
  15.  
  16. if ( $opt{in_place} ) {
  17. $_[0] =~ s/a/A/g;
  18. # .. do more stuff with $_[0]
  19. return;
  20. }
  21. else {
  22. my $str = $_[0];
  23. $str =~ s/a/A/g;
  24. # .. do more stuff with $str
  25. return $str;
  26. }
  27. }

为了避免在上面的if和else块中重复/复制代码,我尝试改进mod_str:

  1. sub mod_str {
  2. my %opt;
  3. %opt = @_[1..$#_];
  4.  
  5. my $ref;
  6. my $str;
  7. if ( $opt{in_place} ) {
  8. $ref = \$_[0];
  9. }
  10. else {
  11. $str = $_[0]; # make copy
  12. $ref = \$str;
  13. }
  14. $$ref =~ s/a/A/g;
  15. # .. do more stuff with $$ref
  16. $opt{in_place} ? return : return $$ref;
  17. }

解决方法

“就地”标志将函数的接口更改为应该是新函数的点.它将简化界面,测试,文档和内部功能,以实现两个功能.用户已经为您做出了这样的选择,而不是必须解析参数并拥有一个大的if / else块.

查看它的另一种方法是将in_place选项始终设置为常量.因为它从根本上改变了函数的行为方式,所以没有明智的情况你会写in_place => $标志.

一旦你这样做,重用变得更加明显.编写一个函数来执行操作.写另一个在副本上调用它.

  1. sub mod_str_in_place {
  2. # ...Do work on $_[0]...
  3.  
  4. return;
  5. }
  6.  
  7. sub mod_str {
  8. my $str = $_[0]; # string is copied
  9.  
  10. mod_str_in_place($str);
  11.  
  12. return $str;
  13. }

猜你在找的Perl相关文章