Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...