in reply to Re^2: Str extract the word between the first and the 2nd '|' character
in thread Str extract the word between the first and the 2nd '|' character

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

my ( $second_word )
Thanks,
Dan.
  • Comment on Re^3: Str extract the word between the first and the 2nd '|' character

Replies are listed 'Best First'.
Re^4: Str extract the word between the first and the 2nd '|' character
by kyle (Abbot) on Apr 11, 2008 at 14:56 UTC

    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.

Re^4: Str extract the word between the first and the 2nd '|' character
by FunkyMonk (Bishop) on Apr 11, 2008 at 14:59 UTC
    $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.