并发 – perl6 grep就像并行程序一样

前端之家收集整理的这篇文章主要介绍了并发 – perl6 grep就像并行程序一样前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在perl6中写了一个类似grep的程序,现在我把它编成了并行处理.但是我遇到了一些问题:即使使用相同的命令行,程序有时会成功,有时会失败.当它成功时,事情对我来说是正常的.当它失败时,我不知道为什么……

这是失败时的错误消息.

  1. > grep6 perl *
  2. An operation first awaited:
  3. in sub MAIN at /Users/xxx/DropBox/bin/grep6 line 28
  4. in block <unit> at /Users/xxx/DropBox/bin/grep6 line 30
  5.  
  6. Died with the exception:
  7. Cannot find method 'Any' on object of type Match
  8. in regex at /Users/xxx/DropBox/bin/grep6 line 34
  9. in sub do_something at /Users/xxx/DropBox/bin/grep6 line 34
  10. in block at /Users/xxx/DropBox/bin/grep6 line 24

代码是:

  1. #!/usr/bin/env perl6
  2.  
  3. constant $color_red = "\e[31m";
  4. constant $color_off = "\e[0m";
  5.  
  6. sub MAIN(Str $pattern,*@filenames){
  7. my $channel = Channel.new();
  8. $channel.send($_) for @filenames; # dir();
  9. $channel.close;
  10. my @workers;
  11. for 1..3 -> $n {
  12. push @workers,start {
  13. while (my $file = $channel.poll) {
  14. do_something($pattern,$file);
  15. }
  16. }
  17. }
  18. await(@workers);
  19. }
  20.  
  21. sub do_something(Str $pattern,Str $filename) {
  22. #say $filename;
  23. for $filename.IO.lines -> $line {
  24. my Str $temp = $line;
  25. if $temp ~~ s:g/ (<$pattern>) /$color_red$0$color_off/ {
  26. say $filename ~ ": " ~ $temp;
  27. }
  28. }
  29. }

我的问题是它为什么有时会失败?

问候

解决方法

这个问题似乎与已知的 rakudo issue for the race method基本相同.

我转自:

  1. if $temp ~~ s:g/ (<$pattern>) /$color_red$0$color_off/ {

至:

  1. if $temp ~~ s:g/ ($pattern) /$color_red$0$color_off/ {

问题似乎消失了.

正如后面提到的Xin Cheng以及同一文档中所描述的那样,更简单的插值在字面上符合文档示例所阐明.发行票修复了以下问题:

  1. my $reg = regex { <$pattern> };
  2. '' ~~ $reg;

导致更新的程序具有类似的解决方法

  1. #!/usr/bin/env perl6
  2.  
  3. constant $color_red = "\e[31m";
  4. constant $color_off = "\e[0m";
  5.  
  6. sub MAIN(Str $pattern,*@filenames){
  7. my $channel = Channel.new();
  8. $channel.send($_) for @filenames; # dir();
  9. $channel.close;
  10. my @workers;
  11.  
  12. # match seems required for pre-compilation
  13. '' ~~ (my regex pat_regex { <$pattern> });
  14.  
  15. for 1..3 -> $n {
  16. push @workers,start {
  17. while (my $file = $channel.poll) {
  18. do_something(&pat_regex,$file);
  19. }
  20. }
  21. }
  22. await(@workers);
  23. }
  24.  
  25. sub do_something(Regex $pat_regex,Str $filename) {
  26. # say $filename;
  27. for $filename.IO.lines -> $line {
  28. my Str $temp = $line;
  29. if $temp ~~ s:g/ ($pat_regex) /$color_red$0$color_off/ {
  30. say $filename ~ ": " ~ $temp;
  31. }
  32. }
  33. }

我为之前提出的明确的EVAL解决方案道歉,我能说的最好的是我的描述要求更好的解决方案.

猜你在找的Perl相关文章