in reply to find words in array
I think you've done a good job with your first Perl script! The comments above on your coding are excellent.
As a suggestion, always begin you scripts with the following:
use strict; use warnings;
I tend to prefer this, instead, which contains the above:
use Modern::Perl;
In either case, these pragmas will catch problematic areas in your script, perhaps saving hours of debugging--among other things.
This being said, consider the following (which doesn't really do anything more than what's already been done above):
use Modern::Perl; my $word = 'a'; my @myNames = qw(Jacob Michael Joshua Matthew Alexander Andrew); if ( $word ~~ @myNames ) { # Using Perl's smart-matching operator say qq|Exact match of "$word" found.|; } elsif ( my @found = grep /\Q$word\E/i, @myNames ) { local $" = "\n"; # Printed between interpolated array's elements say qq|Substring/case-insensitive matches for "$word":\n@found|; } else { say qq|"$word" not found.|; }
Output:
Substring/case-insensitive matches for "a": Jacob Michael Joshua Matthew Alexander Andrew
Actually, the primary difference in the above script is its using Perl's 'smart' operator to check if an element exists in an array.
Hope this helps!
|
|---|