Divesh Rastogi Divesh Rastogi - 2 months ago 16
Perl Question

Check if a patteren contains more than. one string( type array)

How to check if a pattern is an array( contains more than one string) or just a single string?

Consider the following example,

If ( $_ =~ /#define\s+(\S+)\s*(.*)/gi )

#Check if $2 is array or a single string
If ( $2

If it's array than split them into patterns else keep it as it ?

Please suggest.

Regards, Div


A few basic rules and terminology. A regex match is done on a string, which is in a single-valued variable, a scalar. An array variable is associated with a collection of items, representing a list of values. Perhaps you can start with Perl-variable-types in perlintro, and for regex with perlretut.

In the example you show, the variable $_ contains the string to be checked for the pattern. The /g modifier makes the match operator find all occurrences of the match in that string, and returns a list of the matches. Just assign that list to an array

my @matches = $_ =~ /#define\s+(\S+)\s*(.*)/gi;

Now you can check the number of elements in the array

if (@matches == 0) {
    print "There were no matches\n";
elsif (@matches == 1) {
    print "Found one match: $matches[0]\n";
else {
    print "Found more than one: @matches\n";

Another way to check for an empty array is if (not @matches).

However, your regex poses other questions. What kind of input is in your string, and what exactly are you trying to capture? That regex may do something other than what you expect.

If you show some typical input and what you are after a more detailed comment is possible.