atom feed7 messages in org.freebsd.freebsd-questionsRe: Perl question
FromSent OnAttachments
Christopher RuedOct 2, 2000 11:00 am 
Mark OvensOct 2, 2000 11:15 am 
Mark OvensOct 2, 2000 11:25 am 
Andresen,Jason R.Oct 2, 2000 11:36 am 
Christopher RuedOct 2, 2000 2:09 pm 
Mark OvensOct 2, 2000 3:34 pm 
Dirk MyersOct 2, 2000 7:21 pm 
Subject:Re: Perl question
From:Dirk Myers (dir@teleport.com)
Date:Oct 2, 2000 7:21:28 pm
List:org.freebsd.freebsd-questions

"Christopher Rued" held forth that:

When I run the following:

#!/usr/bin/perl $a = "xayxbyxcyxdy"; @s = $a =~ /x.y/; print "\@s is @s\n";

I get:

@s is 1

So, I seem to be getting the truth value rather than the first match in the string.

Actually, you get this list: (1).

Quoting perlop:

# If the /g option is not used, m// in a list context returns a list # consisting of the subexpressions matched by the parentheses in the # pattern, i.e., ($1, $2, $3...).

and:

# When there are no parentheses in the pattern, the return value is # the list (1) for success.

What confuses me is that if I specify the global option, I do not need to use a subexpression. For example, if I run the following code:

#!/usr/bin/perl $a = "xayxbyxcyxdy"; @s = $a =~ /x.y/g; print "\@s is @s\n";

I get:

@s is xay xby xcy xdy

again, from perlop:

# The /g modifier specifies global pattern matching--that is, # matching as many times as possible within the string. How it # behaves depends on the context. In list context, it returns a list # of all the substrings matched by all the parentheses in the regular # expression. If there are no parentheses, it returns a list of all # the matched strings, as if there were parentheses around the whole # pattern.

So, this leaves me with a couple of questions, the main one being: Why the different treatment for single matches and global matches?

This one is easy: because that's how they're defined to work. ;)

and a less important one: Why is there no way to have the first match assigned to a scalar, since we can be sure that there will be at most one match returned?

You're able to get it in other ways -- you can capture it in parens, or you can use $& (and incur the associated performance penalty).

If a match captured by default, though, there'd be no way to just check whether a pattern matched without getting the full match returned (which isn't a big deal for *this* pattern, but *might* be a lot of stuff, which would be an unnecessary performance and memory hit). It's better to make someone actually ask for the string back than to return it whether they want it or not.

Obligatory topic nag: This really belongs on a perl list.

Obligatory RTFM nag: This behavior is covered in the man pages, and in the Camel.

Obligatory disclaimer: I am not a perl guru.

Dirk dir@teleport.com

-- There's a fine line between cleverness and idiocy.

To Unsubscribe: send mail to majo@FreeBSD.org with "unsubscribe freebsd-questions" in the body of the message