smiffy has asked for the wisdom of the Perl Monks concerning the following question:

Hi

I'm having trouble fathoming out how to replace these two lines with a single statement, without having to create the array:

my @foo=$twig->get_xpath($my_xpath); my $bar=$foo[0]->text;

I know the following doesn't work, nor many other permutations I've tried:

my $bar=$twig->get_xpath($my_xpath)[0]->text;

Is what I am trying to do possible and, if so, what is the correct syntax?

TIA

Replies are listed 'Best First'.
Re: XML::Twig - trying to simplify syntax
by merlyn (Sage) on Nov 12, 2010 at 01:27 UTC
    The problem is that your ... ($my_xpath)[0] ... is being interpreted as  ... ($my_xpath)->[0] .... As in, the thing on the left is expected to be an arrayref, which it isn't.

    You can use a slice to get the proper effect:

    my $bar=($twig->get_xpath($my_xpath))[0]->text;
    That'll provide list context to the inner expression, and then extract just the 0'th element from that.

    -- Randal L. Schwartz, Perl hacker

    The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119.

      Excellent, works beautifully. Many thanks for that!

Re: XML::Twig - trying to simplify syntax
by mirod (Canon) on Nov 12, 2010 at 07:06 UTC

    Also: my $bar=$twig->get_xpath($my_xpath, 0)->text;. I see that the optional third argument, although mentioned in the docs, is not properly documented. I'll update it. Thanks