How do I access captured substrings after a successful regex match in Perl?

前端 未结 4 1710
余生分开走
余生分开走 2021-01-24 11:09

I am searching for a string in Perl and storing it in another scalar variable. I want to print this scalar variable. The code below doesn\'t seem to work. I am not sure what is

4条回答
  •  温柔的废话
    2021-01-24 11:37

    I'm unable to replicate your results. What I get is:

    reached here1 
    reached here 3 
    1 
    reached here1 
    reached here 3 
    1 
    reached here1 
    reached here 3 
    1 
    reached here1 
    reached here 3 
    1 
    

    Regardless, it's printing 1 because you've told it to: the print statement to do so is inside the while loop, and what it's printing is an indication of whether or not the pattern matched.

    You'd benefit from indenting your code properly:

    #!/usr/bin/perl
    use strict;
    use warnings;
    
    my $find = '\s{10}[0-9]{2}\s[A-Z]'; #regex. it can also be '\s{10}[0-9]{2}\s[A-Z]' 
                                        #both dont seem to work
    my @element;
    open (FILE, "foo") || die "can't open file \n";
    while (my $line = ) {
        chomp ($line);
        print "reached here1 \n"; # to test whether it reading the program properly
        my $value = $line=~ /$find/ ;
        print "reached here 3 \n"; # to test whether it reading the program properly
        print "$value \n";
    }
    exit;
    

提交回复
热议问题