in reply to Str extract the word between the first and the 2nd '|' character

my ( $second_word ) = $string =~ m{\|([^|]*)\|};

Or, in more detail:

my ( $second_word ) = $string =~ m{ \| # "|" escaped because it's special inside a regexp ( # start capturing [^|]* # some not |'s ) # end capture \| # another "|" }x;

Replies are listed 'Best First'.
Re^2: Str extract the word between the first and the 2nd '|' character
by dani_cv (Acolyte) on Apr 11, 2008 at 14:16 UTC
    Wow...so quick...thank you...

    I just added \s+ to trim the white spaces and this looks perfect..thank you indeed...
    my ( $second_word ) = $string =~ m{\|\s+(^*)\s+\|};

    Dan.
      What is the difference between declaring the variable from normal declaration "my $second_word" from the below declaration?

      my ( $second_word )
      Thanks,
      Dan.

        These two do the same thing:

        my $x; my ( $x );

        The second one is easier to add more variables to later. These are the same:

        my $x ; my $y; my ( $x, $y ); # NOT: my $x, $y

        These two are a little different:

        my $x = foo(); my ( $x ) = foo();

        The difference between them is that the second puts foo() in a list context while the first puts foo() in a scalar context.

        In this particular case (my ($x) = $y =~ /(p)/), the list context is important because that's how the captures come back. In a scalar context, you'd just get a boolean value to tell you whether the pattern matched.

        $foo =~ m// returns different thing depending on context.

        In scalar context it just returns true if $foo matched the regexp and false if it didn't. In list context it returns a list of the things captured by the regexp.

        Declaring a variable like my ( $bar ) = ... forces list context on the right-hand-side of '=', which, in this case forces the match to work in list context.