• Publicidad

Pregunta sobre estructuras

¿Apenas comienzas con Perl? En este foro podrás encontrar y hacer preguntas básicas de Perl con respuestas aptas a tu nivel.

Pregunta sobre estructuras

Notapor natxo » 2011-09-05 09:36 @441

Tengo un archivo (en realidad es el resultado de un comando en un servidor Windows) con estos formato:
Sintáxis: [ Descargar ] [ Ocultar ]
Using text Syntax Highlighting
Writer name: 'System Writer'
   Writer Id: {e8132975-6f93-4464-a53e-1050253ae220}
   Writer Instance Id: {eb6b4c30-aa48-486a-9618-0d1934d180ca}
   State: [1] Stable
   Last error: No error

Writer name: 'Registry Writer'
   Writer Id: {afbab4a2-367d-4d15-a586-71dbb18f8485}
   Writer Instance Id: {d3faa119-61c1-4ec4-b163-68b43efad58b}
   State: [1] Stable
   Last error: No error

Writer name: 'IIS Metabase Writer'
   Writer Id: {59b1f0cf-90ef-465f-9609-6ca8b2938366}
   Writer Instance Id: {d46610d4-d9a9-42c5-87c0-246aa1e352ad}
   State: [1] Stable
   Last error: No error

Writer name: 'Event Log Writer'
   Writer Id: {eee8c692-67ed-4250-8d86-390603070d00}
   Writer Instance Id: {8e45b579-b747-4967-9b4d-17f126bff3bb}
   State: [1] Stable
   Last error: No error
 
Coloreado en 0.000 segundos, usando GeSHi 1.0.8.4
etc...


Me gustaría guardar cada 'párrafo' en una estructura tipo hash, así:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
writer_name    => 'nombre',
writer_id      => 'cadena larga',
writer_inst_id => 'cadena larga',
writer_state   => 'estado',
last_error     => 'tip de error',
Coloreado en 0.002 segundos, usando GeSHi 1.0.8.4


Mi intención es luego poder sacar el writer_name por ejemplo si el writer_state no es X.

Hasta ahora he conseguido sacar los párrafos y guardarlos en un escalar. Luego intento separar líneas de cada párrafo y guardarlas en una variable, pero no lo logro:

Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. use strict;
  2. use warnings;
  3.  
  4. my $vssadmin = "vssadmin list writers" ;
  5.  
  6. # run $vssadmin and save its output in memory for processing
  7. open ( VSS, "$vssadmin |" ) or die "cannot run $vssadmin\n" ;
  8.  
  9. # read the output one paragraph at the time
  10. $/ ="";
  11.  
  12. # and now process the output
  13. while ( my $line = <VSS> ) {
  14.     # dump empty lines and the vssadmin header
  15.     chomp $line;
  16.     next if $line =~ m/.*Microsoft Corp.*$/;
  17.  
  18.     #
  19.     print $line, "\n" ;
  20.     my ($writer_name, $name, $writer_id, $id_guid, $writer_inst_id, $inst_id_guid, $state, $state_value, $last_error, $last_errorvalue ) = split (/:/, $line) ;
  21.  
  22.     print "Writer name:\t $name\n" ;
  23.     print "Writer id:\t $id_guid\n" ;
  24.     print "Writer instance id:\t $inst_id_guid\n\n\n" ;
  25.  
  26. }
  27.  
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4


Me sale esto:

Sintáxis: [ Descargar ] [ Ocultar ]
Using text Syntax Highlighting
Writer name: 'System Writer'
   Writer Id: {e8132975-6f93-4464-a53e-1050253ae220}
   Writer Instance Id: {eb6b4c30-aa48-486a-9618-0d1934d180ca}
   State: [1] Stable
   Last error: No error
Writer name:      'System Writer'
   Writer Id
Writer id:        {eb6b4c30-aa48-486a-9618-0d1934d180ca}
   State
Writer instance id:       No error


Writer name: 'Event Log Writer'
   Writer Id: {eee8c692-67ed-4250-8d86-390603070d00}
   Writer Instance Id: {5eafbd30-bc30-48f7-a03a-0b6ccc17ea8f}
   State: [1] Stable
   Last error: No error
Writer name:      'Event Log Writer'
   Writer Id
Writer id:        {5eafbd30-bc30-48f7-a03a-0b6ccc17ea8f}
   State
Writer instance id:       No error
 
Coloreado en 0.000 segundos, usando GeSHi 1.0.8.4


Como veis, con el primer print() sale todo el párrafo. Luego intento crear un array con split(), pero no se corresponden los valores con lo que tendría que salir.

¿Alguna pista? Llevo un buen rato y no lo veo, la verdad.
saludos,
Natxo Asenjo
natxo
Perlero nuevo
Perlero nuevo
 
Mensajes: 76
Registrado: 2007-08-09 16:22 @723
Ubicación: Países Bajos

Publicidad

Re: Pregunta sobre estructuras

Notapor explorer » 2011-09-05 09:50 @451

El problema está en el split().

Estás indicando que "parta" la cadena de caracteres por los caracteres ':', y que lo asigne a las variables. Eso está bien... pero estás olvidando que en esa cadena de caracteres siguen estando los caracteres de fin de línea y las cadenas que preceden a los ':'.

Si pones estas nuevas líneas, lo verás más claro:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1.     print "Writer name:\t[$name]\n" ;
  2.     print "Writer id:\t[$id_guid]\n" ;
  3.     print "Writer instance id:\t[$inst_id_guid]\n\n\n" ;
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4
JF^D Perl programming & Raku programming. Grupo en Telegram: https://t.me/Perl_ES
Avatar de Usuario
explorer
Administrador
Administrador
 
Mensajes: 14480
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España

Re: Pregunta sobre estructuras

Notapor natxo » 2011-09-05 16:51 @743

Vamos progresando.

Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. use strict;
  2. use warnings;
  3.  
  4. use Data::Dumper;
  5.  
  6. my ( $hash_ref, $writer_name, $writer_id, $writer_inst_id, $state, $last_error );
  7.  
  8. # a paragraph is a line
  9. $/ = "" ;
  10.  
  11. # massage the DATA
  12. # 1st split the paragraphs in lines, save the whole line in @line
  13. # 2nd split @line in keys/values with ":"
  14. while ( my $line = <DATA> ) {
  15.     chomp $line ;
  16.  
  17.     my @line = split (/[\n\r]/, $line) ;
  18.  
  19.     for ( @line ) {
  20.         my ($key, $value)  = split ( /:/) ;
  21.  
  22.         if ( $key =~ m/^.*name$/) {
  23.             $writer_name = $value;
  24.         }
  25.         elsif ( $key =~ m/.*writer id$/i ) {
  26.             $writer_id = $value;
  27.         }
  28.         elsif ( $key =~ m/.*writer instance id$/i ) {
  29.             $writer_inst_id= $value;
  30.         }
  31.         elsif ( $key =~ m/.*state$/i ) {
  32.             $state= $value;
  33.         }
  34.         elsif ( $key =~ m/.*last error$/i ) {
  35.             $last_error= $value;
  36.         }
  37.  
  38.         $hash_ref = { $writer_name => {
  39.                                         "Writer Name"           => $writer_name,
  40.                                         "Writer ID"             => $writer_id,
  41.                                         "Writer Instance ID"    => $writer_inst_id,
  42.                                         "State"                 => $state,
  43.                                         "Last error"            => $last_error,
  44.                                       }
  45.                     } ;
  46.     }
  47.  
  48.     print Dumper $hash_ref;
  49. }
  50.  
  51.  
  52. __DATA__
  53. Writer name: 'System Writer'
  54.    Writer Id: {e8132975-6f93-4464-a53e-1050253ae220}
  55.    Writer Instance Id: {eb6b4c30-aa48-486a-9618-0d1934d180ca}
  56.    State: [1] Stable
  57.    Last error: No error
  58.  
  59. Writer name: 'Registry Writer'
  60.    Writer Id: {afbab4a2-367d-4d15-a586-71dbb18f8485}
  61.    Writer Instance Id: {d3faa119-61c1-4ec4-b163-68b43efad58b}
  62.    State: [1] Stable
  63.    Last error: No error
  64.  
  65. Writer name: 'IIS Metabase Writer'
  66.    Writer Id: {59b1f0cf-90ef-465f-9609-6ca8b2938366}
  67.    Writer Instance Id: {d46610d4-d9a9-42c5-87c0-246aa1e352ad}
  68.    State: [1] Stable
  69.    Last error: No error
  70.  
  71. Writer name: 'Event Log Writer'
  72.    Writer Id: {eee8c692-67ed-4250-8d86-390603070d00}
  73.    Writer Instance Id: {8e45b579-b747-4967-9b4d-17f126bff3bb}
  74.    State: [1] Stable
  75.    Last error: No error
  76.  
  77.  
Coloreado en 0.002 segundos, usando GeSHi 1.0.8.4


Sintáxis: [ Descargar ] [ Ocultar ]
Using bash Syntax Highlighting
  1. $ perl vssaddmin.pl
  2. $VAR1 = {
  3.           ' \'System Writer\'' => {
  4.                                    'Last error' => ' No error',
  5.                                    'Writer ID' => ' {e8132975-6f93-4464-a53e-1050253ae220}',
  6.                                    'Writer Name' => ' \'System Writer\'',
  7.                                    'State' => ' [1] Stable',
  8.                                    'Writer Instance ID' => ' {eb6b4c30-aa48-486a-9618-0d1934d180ca}'
  9.                                  }
  10.        };
  11. $VAR1 = {
  12.          ' \'Registry Writer\'' => {
  13.                                      'Last error' => ' No error',
  14.                                      'Writer ID' => ' {afbab4a2-367d-4d15-a586-71dbb18f8485}',
  15.                                      'Writer Name' => ' \'Registry Writer\'',
  16.                                      'State' => ' [1] Stable',
  17.                                      'Writer Instance ID' => ' {d3faa119-61c1-4ec4-b163-68b43efad58b}'
  18.                                    }
  19.        };
  20. $VAR1 = {
  21.          ' \'IIS Metabase Writer\'' => {
  22.                                          'Last error' => ' No error',
  23.                                          'Writer ID' => ' {59b1f0cf-90ef-465f-9609-6ca8b2938366}',
  24.                                          'Writer Name' => ' \'IIS Metabase Writer\'',
  25.                                          'State' => ' [1] Stable',
  26.                                          'Writer Instance ID' => ' {d46610d4-d9a9-42c5-87c0-246aa1e352ad}'
  27.                                        }
  28.        };
  29. $VAR1 = {
  30.          ' \'Event Log Writer\'' => {
  31.                                       'Last error' => ' No error',
  32.                                       'Writer ID' => ' {eee8c692-67ed-4250-8d86-390603070d00}',
  33.                                       'Writer Name' => ' \'Event Log Writer\'',
  34.                                       'State' => ' [1] Stable',
  35.                                       'Writer Instance ID' => ' {8e45b579-b747-4967-9b4d-17f126bff3bb}'
  36.                                     }
  37.  
Coloreado en 0.004 segundos, usando GeSHi 1.0.8.4


Así funciona siempre y cuando ejecute el print Dumper $hash_ref dentro del bucle while(); no entiendo por qué :-), si alguien tiene a bien explicarlo se lo agradecería. Según como lo entiendo, voy procesando los datos y llenando el hash con claves únicas. Si ejecuto el print Dumper $hash_ref al final, sólo veo el último elemento del hash. Extraño.
saludos,
Natxo Asenjo
natxo
Perlero nuevo
Perlero nuevo
 
Mensajes: 76
Registrado: 2007-08-09 16:22 @723
Ubicación: Países Bajos

Re: Pregunta sobre estructuras

Notapor explorer » 2011-09-05 17:23 @766

Estás reescribiendo el valor del hash, en cada vuelta. Por eso sólo hay un único valor: el último.

Cambia la línea 38 por
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1.         $hash_ref->{ $writer_name } = {
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4
y la 45 por
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1.                     ;
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4
JF^D Perl programming & Raku programming. Grupo en Telegram: https://t.me/Perl_ES
Avatar de Usuario
explorer
Administrador
Administrador
 
Mensajes: 14480
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España

Re: Pregunta sobre estructuras

Notapor natxo » 2011-09-06 02:26 @143

Perfecto. Ahora lo entiendo, estaba modificando el hash completo en cada vuelta en vez de añadir un elemento.

Gracias por tu ayuda, como siempre.
saludos,
Natxo Asenjo
natxo
Perlero nuevo
Perlero nuevo
 
Mensajes: 76
Registrado: 2007-08-09 16:22 @723
Ubicación: Países Bajos


Volver a Básico

¿Quién está conectado?

Usuarios navegando por este Foro: No hay usuarios registrados visitando el Foro y 21 invitados

cron