Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
304 views
in Technique[技术] by (71.8m points)

Perl set counter to match in loop

How can I set a $counter++ to hash unless is 1? in this code:

use strict;
    use warnings;    

    my @filestwo = glob("*.xml");
    my $result = @filestwo;          

    my $count = 0;
    my %justone;
    foreach my $domain (@filestwo) {
      open my $in, '<', $domain or die "Open fail on $domain $!
";
        my @linestwo = <$in>;        

            for my $line (@linestwo) {

                if($line =~ /Domain:s([a-z].+)/){
                  $count++;
                  print "Number:$count Your TLD $1!
" unless $justone{$1}++;
                }                

            }

}

The output:

Number:1 Your TLD one.com!
Number:3 Your TLD three.com!
Number:5 Your TLD two.com!

Should be:

Number:1 Your TLD one.com!
Number:2 Your TLD three.com!
Number:3 Your TLD two.com!

Explanation about the code:

  • Open 3 files .xml (In every file exist duplicate pattern)
  • Create a hash %justone;
  • Search from the array if the match the pattern: domain
  • If match and in the next iteration match again the same pattern, just print 1 with unless $justone{$1}++;

My problem, I can't set a counter just for the match relation unless hash.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you only want to increment unless some condition is met, you should mention that in your code.

Using the postfix foo() unless condition(); syntax means the condition will only refer to the previous statement, not the entire scope ( which would arguably be insane to parse ).

So print '...' unless $foo is the same as unless( $foo ){ print '...'; }.

Thus, if you want to include more than one statement in your unless condition, you need to use curly braces: unless ( $foo ) { # as many lines as desired }

If I understood your question correctly, you want to do:

unless ( $justone{$1}++ ){
    $count++;
    print "Number:$count Your TLD $1!
"
}

This will increment only if the condition was met, and lead to the desired output. I would suggest to use a named variable for what you've captured in $1 to make it more readable, though.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...