How to assign the match of string to another variable in perl?

Tolgar used Ask the Experts™
I try to assign the matched result to another variable but instead the other variable gets the value 1 which means that there is match.

Here is the example:

my ($clientRoot) = $infoArray[3] =~ /Client root:\s.*/;

Open in new window

$infoArray[3]  is something like this: Client root: some/path/in/here

Expected result for $clientRoot:


Open in new window

Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
This should work:

my $clientRoot= $1 if $infoArray[3] =~ /Client root:\s(.*)/;


I normally use my other pattern but why didn't it work in here? Is it because I have an array instead of a single variable?
Or, more verbosely:
if ($infoArray[3] =~ m{Client root:\s+(.*)}) {
    $clientRoot = $1;

Open in new window

Or, more compactly:
my ($clientRoot) = ($infoArray[3] =~ m{Client root:\s+(.*)});

Open in new window

Become a Certified Penetration Testing Engineer

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

You can do it this way:

my ($clientRoot) = $infoArray[3] =~ /Client root:\s(.*)/;

Only difference is the capturing group in the regex.
Your original pattern did not work because you forgot the capturing parens (see my second option for the correct equivalent of your original idea (which I missed when reading the question)).  The parens around the match may not be required in mine but I usually include them just to make precedence explicit.
my ($clientRoot) = ($infoArray[3] =~ m{Client root:\s+(.*)});

Open in new window

ǩa̹̼͍̓̂ͪͤͭ̓u͈̳̟͕̬ͩ͂̌͌̾̀ͪf̭̤͉̅̋͛͂̓͛̈m̩̘̱̃e͙̳͊̑̂ͦ̌ͯ̚d͋̋ͧ̑ͯ͛̉Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015
It did work, but the only thing output is the entire match. This is because you didn't specify any capture groups (parentheses, like brendonfeeley demonstrated). When you capture the result of a regex in list context in Perl, the capture groups are what are output to the variable. Since you didn't specify any groups, the output reverted to the overall match.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial