0

Hi I have these strings and several other strings in an array.

    revised_1.4_1.4-1.05-jan
    revised_1.5_1.8-before
    revised_1.5_1.8-after
    revised_1.5_0.7-mid
    deleted&reviewed_0.9-0.8-1.05-jan
    deleted&reviewed_1.6_1.6-before
    deleted&reviewed_0.5_1.8-after
    deleted&uploaded_0.8_1.9-midweek
    deleted&uploaded_1.0_1.3-offweek
    accessedbeforesecondquarter_0.8._1.6-jan
    accessedbeforesecondquarter_0.9_1.7-feb

I need to keep one of the almost similar strings in the array. How can I code to get this array?

    revised_1.4_1.4-1.05-jan 
    deleted&reviewed_0.9-0.8-1.05-jan
    deleted&uploaded_0.8_1.9-midweek
    accessedbeforesecondquarter_0.8._1.6-jan

Here's my code and it doesn't seem to work fine for me to save the strings into an array.

my %seen;
my @strings = grep !$seen{ substr($_,0,2) }++, @strings;

1 Answer 1

1

keeping the spirit of what you tried:

my %seen;
my @result = grep {! $seen{(split "_",$_)[0]}++} <DATA>;
print @result;

__DATA__
revised_1.4_1.4-1.05-jan
revised_1.5_1.8-before
revised_1.5_1.8-after
revised_1.5_0.7-mid
deleted&reviewed_0.9-0.8-1.05-jan
deleted&reviewed_1.6_1.6-before
deleted&reviewed_0.5_1.8-after
deleted&uploaded_0.8_1.9-midweek
deleted&uploaded_1.0_1.3-offweek
accessedbeforesecondquarter_0.8._1.6-jan
accessedbeforesecondquarter_0.9_1.7-feb

result:

revised_1.4_1.4-1.05-jan
deleted&reviewed_0.9-0.8-1.05-jan
deleted&uploaded_0.8_1.9-midweek
accessedbeforesecondquarter_0.8._1.6-jan
Sign up to request clarification or add additional context in comments.

2 Comments

Can you explain (split "_",$_)[0]}++ this code. I was use decrement operator instead of ++ it is also work. What is the meaning of the ++ operator in your code?
@aja (split "_", $_) returns a list split with '_' with [0] you are taking the first element of the list and then increment the count for the hash. Any non-zero number is true in Perl in boolean context. So '!1' or '!-1' returns false. grep returns the elements that are true.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.