Hi there, I am new to this forum, and to Perl as a whole. I've been practicing programming in Perl today, using exercises from practicepython.org (yes, I know Python is not Perl, but I like the broad nature of the exercises on there and I had no idea where to look for up to date Perl-specific exercises :-P).
I have just finished doing this exercise: http://www.practicepython.org/exercise/2014/03/05/05-list-overlap.html. The exercise is basically finding the values that two randomly generated lists have in common.
I figured out how to do this using regexps (which are awesome btw) but I haven't been able to reduce the code necessary for matching the values to one line, which is one of the optional objectives of the exercise. 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? Or is this as short as it gets? I would also like to know if using regexps for this is less or more efficient (performance-wise) than just using a for loop. This is the code I have as of now:
#!/usr/bin/env perl # This script should check what elements are common between two lists use strict; use warnings; # Lists of random numbers my @input=map {int(rand($_))} (1..100); my @valuesToMatch=map {int(rand($_))} (1..100); print "-----list 1 is:-----\n@input\n-----and list 2 is:-----\n@values +ToMatch\n"; # Match the common values my $matchString = sprintf "\\b%s", join("\\b\|\\b",@valuesToMatch); my @result = join(" ", @input) =~ /$matchString/g; # Return result print "---------------The matching numbers are:---------------\n@resul +t\n" ;
In reply to one line to check for common list values by dollar_sign
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |