Issue
I am literally brand new to Perl. I have the following...
#!/usr/bin/perl
#config file
$config = "$ENV{'HOME'}/.config/.wallpaperrc";
open my $handle, '<', $config;
chomp(my @lines = <$handle>);
close $handle;
@regular = map(/^regular\.roll (.*)$/, @lines);
print(@regular);
It works but it seems awkward and improper to be using an array when I am only expecting one match and only want one match. If I make @regular scalar then the function returns the number of matches instead.
I tried to search for the answer but the results are muddied with all the questions using Perl grep within Bash.
Solution
You can capture a single match by assigning to a scalar in list context
($regular) = map(/^regular\.roll (.*)$/, @lines);
The parentheses on the left hand side are important, otherwise you are imposing scalar context on the right hand size and the result will be something else, like the number of elements.
If you're trying to capture the first match from grep
(but not map
) and you are more comfortable using Perl modules, the first
function in the List::Util
package returns the first match, and is more efficient than calling grep
and discarding all the extra matches.
use List::Util 'first';
...
$regular = first { /pattern/ } @input;
Answered By - mob Answer Checked By - Clifford M. (WPSolving Volunteer)