Ad-vic
Ad-vic

Reputation: 529

extract first word from a sentence and store it

i am extracting first word from a line using regex in Perl

for my $source_line (@lines) {
    $source_line =~ /^(.*?)\s/
}

But I want to store the first word into a variable

when I print the below code, I get correct output

print($source_line =~ /^(.*?)\s/)

when I want to store in $i and print it, I get output as 1.

my $i =  ($source_line =~ /^(.*?)\s/);
print $i;

How do the store the first word into a temporary variable

Upvotes: 0

Views: 1896

Answers (2)

Hunter McMillen
Hunter McMillen

Reputation: 61512

It all comes down to context, this expression:

$source_line =~ /^(.*?)\s/

returns a list of matches.

When you evaluate a list in list context, you get the list itself back. When you evaluate a list in scalar context, you get the size of the list back; which is what is happening here.

So changing your lhs expression to be in list context:

my ($i) = $source_line =~ /^(.*?)\s/;

captures the word correctly.

There were recently a few articles on Perl Weekly related to context, here is one of them that was particularly good: http://perlhacks.com/2013/12/misunderstanding-context/

Upvotes: 1

ikegami
ikegami

Reputation: 385575

You need to evaluate the match in list context.

my ($i) = $source_line =~ /^(.*?)\s/;

my ($i) is the same as (my $i), which "looks like a list", so it causes = to be the list assignment operator, and the list assignment operator evaluates its RHS in list context.


By the way, the following version works even if there's only one work and when there's leading whitespace:

my ($i) = $source_line =~ /(\S+)/;

Upvotes: 2

Related Questions