BloozLawyer
BloozLawyer

Reputation: 3

perl regex capture returns same value (1)

I am using perl 5.28. This is my script

 #!/usr/bin/perl
 use strict; use warnings;
 
my @files = glob("msa_vcf/*vcf");

foreach my $f (@files){
    my $wk = $f =~ /(\d+)/;
    print "$wk    $f\n";
}

Pretty simple stuff but this is what it prints

1    msa_vcf/1.vcf
1    msa_vcf/10.vcf
1    msa_vcf/11.vcf
1    msa_vcf/12.vcf
1    msa_vcf/13.vcf
1    msa_vcf/14.vcf
1    msa_vcf/15.vcf
1    msa_vcf/16.vcf
1    msa_vcf/17.vcf
1    msa_vcf/18.vcf
1    msa_vcf/19.vcf
1    msa_vcf/2.vcf
1    msa_vcf/20.vcf

If I do this in python with the re library, I get the correct value being captured. The regex syntax is the same, so what's going on?

Upvotes: 0

Views: 104

Answers (1)

ikegami
ikegami

Reputation: 386461

You are evaluating the match in scalar context. As a result, it is returning whether the match was successful or not.

You want to evaluate the match in list context. This is done by making the left-hand side of the assignment "list-like".

my ($wk) = $f =~ /(\d+)/;

Upvotes: 3

Related Questions