正则表达式匹配不会在perl中产生输出

如何解决正则表达式匹配不会在perl中产生输出

我有一个看起来像这样的测试文件:

t # 3-0,1
v 0 0
v 1 19
v 2 2
u 0 1 2
u 0 2 2
u 1 2 2
t # 3-1,1
v 0 0
v 1 15
v 2 2
u 0 1 2
u 0 2 2
u 1 2 2
t # 3-2,1
v 0 0
v 1 17
v 2 2
u 0 1 2
u 0 2 2
u 1 2 2
t # 3-3,1
v 0 0
v 1 18
v 2 7
u 0 1 2
u 0 2 2
u 1 2 2

我编写了以下代码来匹配交易的后三行(每笔交易均以t #开头)

#!/usr/bin/perl -w
    
use strict;
    
my $input = shift @ARGV or die $!; 
    
open (FILE,"$input") or die $!;

LOOP: while (<FILE>) {
         if (m/^(t\h*#\h*[0-9,\h-]+)/) {
             my $transaction_id = $1;
             while (<FILE>) {
                if (m/^(u\h+[0]\h+[1]\h+[2])/) {
                    my $edge_1 = $1;
                    while (<FILE>) {
                        if (m/^(u\h+[0]\h+[2]\h+[2])/) {
                            my $edge_2 = $1;
                            while (<FILE>) {
                                if (m/^(u\h+[1]\h+[2]\h+[2])/) {
                                    my $edge_3 = $1;
                                    print $transaction_id . "\t" . $edge_1 . "\t" . $edge_2 . "\t" . $edge_3 . "\n";
                                    next LOOP;
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
    
close FILE;

但是,它不会打印任何结果。当我编译程序时,它运行时没有错误。我的最终目标是产生这样的输出,在这里我输出子图“ u 0 1 2”,“ u 0 2 2”和“ u 1 2 2”的边:

t # 3-0,1   u 0 1 2   u 0 2 2   u 1 2 2
t # 3-1,1   u 0 1 2   u 0 2 2   u 1 2 2
t # 3-2,1   u 0 1 2   u 0 2 2   u 1 2 2
t # 3-3,1   u 0 1 2   u 0 2 2   u 1 2 2

解决方法

一种方法:将事务的所有行都保存在缓冲区中,当您进入新的事务ID时,将前一个以及该缓冲区的后三行一起存储

use warnings;
use strict;
use feature 'say';

my (@transactions,@trans_lines,$tid);

while (<>) { 
    chomp;

    if (/^(t\s*#\s*[0-9,\s-]+)/) { 
        if (not $tid) {      
            $tid = $1;   # the very first one starts
            next;
        }

        # Store previous id and its last three lines,reset
        push @transactions,[ $tid,@trans_lines[-3..-1] ];
        $tid = $1; 
        @trans_lines = ()
    }   

    push @trans_lines,$_; 
}


say "@$_" for @transactions;

这会将所有事务存储在一个数组中,因此可以轻松地进行迭代并维护文件中的顺序。这支持使用问题中显示的结果。但是对于数组,不能轻易地引用特定的数组,如果有兴趣能够查找特定的id,可以考虑使用数组引用的哈希代替,例如在related problem中。

上面的代码依赖于事务中始终存在三行,如问题中所隐含的那样。我建议添加支票。

结构while (<>)读取命令行或STDIN上给定的所有文件的行。


对发布代码的一些评论

  • use warnings;比使用-w switch

  • $! variable保存错误字符串。尽管确实应该普遍使用它,但是如果@ARGV为空,则shift返回undef且没有错误;因此未设置$!。相反,要做类似的事情

    my $file = shift @ARGV  // die "Usage: $0 file\n";
    

    或者更好的是,使用更完整的用法消息等调用您的例程。

  • 使用词法文件句柄open my $fh,'<',$file or die $!;,因为它们在多种方面明显优于全局(FH

  • 无需对单标量变量加双引号,因为它无论如何都会被求值(尽管在某些情况下,过多的引号甚至可能导致细微的问题)

  • 从同一资源(此处为文件句柄)读取的嵌套循环是合法的,并且具有其用途,但会增加一层复杂性并使代码难以跟踪。我会非常非常谨慎地使用它。多层嵌套会增加更多的复杂性。

我不容易理解为什么问题中的代码不起作用。添加打印报表?

,

您的代码就是这样的输出:

t # 3-0,1  u 0 1 2 u 0 2 2 u 1 2 2
t # 3-1,1  u 0 1 2 u 0 2 2 u 1 2 2
t # 3-2,1  u 0 1 2 u 0 2 2 u 1 2 2
t # 3-3,1  u 0 1 2 u 0 2 2 u 1 2 2

所以看来问题出在您没有向我们展示的东西上。输入文件可能来自其他系统,并且具有系统无法识别的行尾。

您的嵌套while循环和if条件使代码变得比所需的更为复杂(因此难以维护)。您可以使用以下内容在一个循环中完成所有操作:

#!/usr/bin/perl

use strict;
use warnings;

my $input = shift @ARGV or die $!;

open (my $fh,$input) or die $!;

my ($transaction_id,$edge_1,$edge_2,$edge_3);

while (<$fh>) {
  if (m/^(t\h*#\h*[0-9,\h-]+)/) {
    $transaction_id = $1;
  } elsif (m/^(u\h+[0]\h+[1]\h+[2])/) {
    $edge_1 = $1;
  } elsif (m/^(u\h+[0]\h+[2]\h+[2])/) {
    $edge_2 = $1;
  } elsif (m/^(u\h+[1]\h+[2]\h+[2])/) {
    $edge_3 = $1;
  }

  if ($transaction_id and $edge_1 and $edge_2 and $edge_3) {
    print "$transaction_id\t$edge_1\t$edge_2\t$edge_3\n";
    ($transaction_id,$edge_3) = (undef) x 4;
  }
}

(注意,我也将-w替换为use warnings,转而使用词法文件句柄和open()的三个参数版本。所有这些都是Modern Perl最佳实践)

,

请尝试以下操作:

#!/usr/bin/perl -w

my $ref;
open(FH,shift) or die;
while (<FH>) {
    chop;
    if (/^t\s*#/) {            # if a new transaction starts
        $ref = [];             # then create a new reference to an array
        push(@refs,$ref);     # and memorize the reference
    }
    push(@$ref,$_);           # append the line to the current array
}
for $ref (@refs) {
    print(join(" " x 4,$ref->[0],$ref->[-3],$ref->[-2],$ref->[-1]),"\n");
}

输出:

t # 3-0,1    u 0 1 2    u 0 2 2    u 1 2 2
t # 3-1,1    u 0 1 2    u 0 2 2    u 1 2 2
t # 3-2,1    u 0 1 2    u 0 2 2    u 1 2 2
t # 3-3,1    u 0 1 2    u 0 2 2    u 1 2 2
,

定义正则表达式模式$skip$data$tran,遍历数据,组装交易行并在新交易开始时推入数组

use strict;
use warnings;
use feature 'say';

use Data::Dumper;

my $skip = qr/^v \d+ \d+/;
my $data = qr/^u \d+ \d+ \d+/;
my $tran = qr/^t # \d-\d,\d/;

my @array;
my $line = <DATA>;

chomp($line);

 while( <DATA> ) {
    next if /$skip/;
    chomp;
    $line .= '  ' . $_ if /$data/;
    if( /$tran/ ) {
        push @array,$line;
        $line = $_;
    }
}

push @array,$line;

say Dumper(\@array);

__DATA__
t # 3-0,1
v 0 0
v 1 19
v 2 2
u 0 1 2
u 0 2 2
u 1 2 2
t # 3-1,1
v 0 0
v 1 15
v 2 2
u 0 1 2
u 0 2 2
u 1 2 2
t # 3-2,1
v 0 0
v 1 17
v 2 2
u 0 1 2
u 0 2 2
u 1 2 2
t # 3-3,1
v 0 0
v 1 18
v 2 7
u 0 1 2
u 0 2 2
u 1 2 2

输出

$VAR1 = [
          't # 3-0,1  u 0 1 2  u 0 2 2  u 1 2 2','t # 3-1,'t # 3-2,'t # 3-3,1  u 0 1 2  u 0 2 2  u 1 2 2'
        ];

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-