siddheshsawant has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks,

I was working on regex in perl and I am stuck at one problem. The code that I wrote is as follows:

#!/usr/bin/perl -w use strict; my $str = "TEST_ENVIRONMENT OS_NAME=AIX BUILD_TYPE= KERNEL_BI +TNESS=64 USER_BITNESS=32 OS_RELEASE=6.1.0.0 CPU_CLASS=powerp +c MACHINE_CLASS=IBM,8203-E4A HOSTNAME=lcla114 NUM_CPUS=5 +CUSTOM= "; my $machine_class = ($str =~ /MACHINE_CLASS=\s*(\w*)/); print "MACHINE CLASS=$machine_class";

As a output of above code I am not getting IBM . Instead, I am getting number 1. So where I am doing mistake? I want to match the string and extract the required value and then have to store that value in the variable and print it.

If anybody knows where I am doing that mistake then let me know about.Thanks in advance !!!!!

Replies are listed 'Best First'.
Re: Regular Expression
by ikegami (Patriarch) on May 14, 2010 at 15:15 UTC

    Change
    my $machine_class
    to
    my ($machine_class)
    to cause the match to be evaluated in list context.

      Thanks a lot .....That worked for me
Re: @ Regular Expression
by kennethk (Abbot) on May 14, 2010 at 15:17 UTC
    You are having issues with list vs. scalar context. When you write

    my $machine_class = ($str =~ /MACHINE_CLASS=\s*(\w*)/);

    Perl sees you are setting a scalar, and so interprets the right hand side in that context. Since the right hand side is a list, it assigns the size of the list (1) to $machine_class. You can put the assignment in list context by wrapping your variable in parentheses:

    my ($machine_class) = ($str =~ /MACHINE_CLASS=\s*(\w*)/);

    See Extracting matches in perlretut. You can read more about context in Perl in Context in perldata or Context tutorial from the Tutorials.

Re: @ Regular Expression
by wfsp (Abbot) on May 14, 2010 at 15:15 UTC
    Nearly! Try
    my ($machine_class) = $str =~ /MACHINE_CLASS=\s*(\w*)/;
Re: @ Regular Expression
by marto (Cardinal) on May 14, 2010 at 15:16 UTC
Re: @ Regular Expression
by toolic (Bishop) on May 14, 2010 at 15:16 UTC
    Evaluate in list context:
    my ($machine_class) = ($str =~ /MACHINE_CLASS=\s*(\w*)/);