Perl SimpleXML: cómo acceder a un valor sin clave
Frecuentes
Visto 208 veces
0
I've got an XML file, When I do a print Dumper
on my now $data->{Foo}
, Obtengo el siguiente resultado.
$VAR1 = [
{
'Bar' => {
...etc...
}
},
{
'Bar' => {
...etc2...
}
}
];
How do I print what's under the second Bar? I tried:
$data->{Foo}{1}->{Bar}
But that's incorrect syntax.
Gracias,
Dan
1 Respuestas
4
You're going to get in trouble if you leave out the first '->'.
Si usted dice $foo->[0]
Perl thinks that foo
is a scalar that's a reference to an array, and then returns the first element of that referenced array.
Si usted dice $foo[0]
Perl thinks that foo
is an array, and returns it's first element.
You also need to be careful about []
vs {}
. []
are for array lookups, {}
are for hash lookups. Perl can convince an array that it's a hash if it really wants to, with surprising results sometimes.
So, given all that, you need to say something like this:
$data->{Foo}[1]{Bar};
or more pedantically:
$data->{Foo}->[1]->{Bar};
Given the comments below, the first form is preferred for what I think are pretty obvious reasons. See 'Using References' in perldoc perlref
para más información.
contestado el 03 de mayo de 12 a las 19:05
Looking at this again, you may be able to leave out all '->'s after the first one, resulting in $data->{Foo}[1]{Bar};
- Sean O'Leary
You can (and I dare say debemos) leave out all ->
después del primero. $data->{Foo}[1]{Bar}
es lo mismo. - derobert
Yeah, I think should is correct. I've just been using a few other languages lately, and wasn't 100% until I tested it. Post first, answer questions later. :) - Sean O'Leary
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas perl hash simplexml or haz tu propia pregunta.
Also tried a few different variations: $data->{foo}->{bar}[1] $data->{foo}->{1}->{bar} - dlite922
{bar}
no es lo mismo que{Bar}
. Please say what you mean and mean what you say. - mobsorry, excuse the case sensitivity mistake. it's corrected now. - dlite922