On 12/05/2011 03:25, siegfr...@heintze.com wrote:
>
> Darn -- I forgot to switch to plain text again. I hope this does not
> appear twice -- I apologize if it does!

Hi Siegfried.

HTML messages are fine on this forum, although it is much better to 
present code in a monospaced font.

> This works and produces the desired result (I've simplified it a bit):
> 
> 
> $default= ((((`grep pat file-name`)[0])=~/[0-9]+/)[0]);
> 
> 
> Why does it take so many parentheses?

It works fine as

  $default = ((`grep pat file-name`)[0] =~ /[0-9]+/)[0];

> I don't think it should work, however.

??

> (1) Why cannot I just index the results of the sub-process directly and
> say `grep pat file-name`[0]? If Perl is confused I would think I might
> need to explicitly convert it like this:
>    @{`grep pat file-name`}[0]
> but that does not work. I think it should.

It is all about context. `command` in isolation imposes scalar context,
and indexing it as such makes as much sense as "command"[0]. Enclosing
it in parentheses imposes list context, which can then be indexed
successfully.

@{`command`}[0] is attempting to dereference `command` as an array
reference, when it is simply a text string. Moreover, if it was valid
syntax, you would be accessing an array slice of one element, better
wriiten as ${$array_ref}[0]

> (2) I have the same question about the =~ operator -- it returns an
> array too. So why cannot I just type
> print @{$a=~/([0-9]+)/}[0] ?

The match operator is also context-sensitive. Its return also depends on
whether the right-hand side is m//, s//, or tr//. Furthermore, nothing
returns an array - only a list or an array reference. If there are no
captures in the regex, m// returns true or false (1 or '') in scalar
context and the lists (1) or () in list context.

As above, your code is attempting to dereference a simple scalar value
as if it was an array reference. If you had 'strict refs' in place you
would have a run time error message.

> Instead I have to type
>   print (($a=~/([0-9]+/)[0]);

(You have a missing closing parenthesis in the regex, but it is clear
what you mean.)

Because print is a list operator that returns true or false according to
its success status. If the print is successful, then

  print($a=~/([0-9]+/)[0];

is the same as

  1[0]

which throws a syntax error.

You have a fundamental misunderstanding about the distinction between a
Perl list and an array. Reading perldoc -q "list and an array" should
help you. It is here on line

  
<http://perldoc.perl.org/perlfaq4.html#What-is-the-difference-between-a-list-and-an-array%3F>

Cheers,

Rob

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to