P is for Practical | |
PerlMonks |
Re: one line to check for common list valuesby haukex (Archbishop) |
on Feb 25, 2017 at 19:24 UTC ( [id://1182835]=note: print w/replies, xml ) | Need Help?? |
Welcome to Perl and the Monastery, dollar_sign! Just a small tip on posting: Thank you for using <code> tags for the code, but please don't add line numbers. Perl has excellent documentation, see perldoc.perl.org, and the command line tool perldoc. For example, typing perldoc -q intersection at the command line brings up this FAQ: How do I compute the difference of two arrays? How do I compute the intersection of two arrays? One of the pieces of Perl philosophy is TIMTOWTDI, There Is More Than One Way To Do It, so if you want to use a regex to find matches, that's ok, but see the performance comparison below. Note that if your input wasn't limited to integers, your regex has one potential problem, see what happens when you set my @input = (1.23) and my @valuesToMatch = (23). I wrote about the generation of regexes here I would also like to know if using regexps for this is less or more efficient (performance-wise) than just using a for loop. The go-to module for this is Benchmark. Here is a comparison of the performance of using regular expressions, hashes, and grep. Note how the hash approach clearly wins!
Update: Example output (whitespace edited for brevity):
Would it be possible to reduce the amount of code necessary to find the common values between the two arrays to only one line of Perl? Sure, it's possible to jam it all into one line, the AM showed one way to do it for the "regex" approach (Update: tybalt89 showed a few more, but benchmark them and you'll see all three of them are less efficient than all of the above). It's also possible in the above "grep" solution using two nested greps, but for the "hash" solution, you'll need multiple statements, even if you jam them all into one line :-) I had no idea where to look for up to date Perl-specific exercises One might be HackerRank, or perhaps Rosetta Code.
In Section
Seekers of Perl Wisdom
|
|