• Publicidad

Problema para imprimir en archivo

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

Problema para imprimir en archivo

Notapor STM » 2010-08-03 04:34 @232

Hola,

Estoy escribiendo un programa que lea varios archivos (mismo formato) recuperar solo cierta información y luego la imprima en un nuevo archivo.

Los primero datos del formato deben repetirse varias veces ya que solo las dos últimas columnas cambian de valor todo el tiempo.

El formato final sería algo así:
Sintáxis: [ Descargar ] [ Ocultar ]
Using text Syntax Highlighting
Name  voltaje time  hold  setup delay slope
XXXX  yyyy     hhh    nn   lll    ppp   rrrr
Coloreado en 0.000 segundos, usando GeSHi 1.0.8.4


Sin embargo, Perl dice que no puede imprimir en el archivo que yo le designo.

Hay otra pregunta que también quisiera formarles: cada vez que recupero un valor en el if() yo lo almaceno en una variable pero fuera del if() la variable no es conocida, así que no sé cómo hacer que la variable sea conocida para que al final ella sea imprimida en el archivo de salida.

¿Podrían decirme cuál es el error por el cual Perl no puede abrir el archivo y cómo hacer para que Perl reconozca fuera del if() el valor de las variables dataXXX?

Gracias de antemano.

Mi código es el siguiente:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. #!/usr/bin/perl
  2. #use strict;
  3. use warnings;
  4. use Cwd;  
  5. $dir= getcwd;
  6. $Vstress='1.32';
  7. @name=split(/\//,$dir);
  8. @entrada=('1', '2');
  9. @HOLD=('1','2','3','4','5');
  10. @SETUP=('22','23','24','25');
  11. ##################
  12. @lista=('zoneA','zoneB','SP0','SP50','SP100');
  13. @age=('2','0.2','0.02');
  14. @agingtype=('hci=0 nbti=1','hci=1 nbti=0','hci=1 nbti=1');
  15. @agingtypex=('nbti','hci','NBTI+HCI');
  16. @capacitance=('0.0008e-12','0.0141e-12','0.0495e-12');
  17. $lsfout_high='extract.cvs';
  18. $data3='87';
  19. $data11='87';
  20. $lista1='12';
  21. ############
  22.  
  23.  
  24. #########
  25.  
  26. for ($n=0; $n<@entrada; $n++)
  27. {
  28.  
  29. if ($entrada[$n]==1)
  30.  
  31. {$entrada=$dir."/charac_CSHT_Fresh_high.cir";
  32.  $entradaxx=charac_DATA_high;
  33.  
  34.  
  35. for ($iii=0; $iii<@agingtype; $iii++ )
  36. {
  37.  
  38.  
  39. for ($ii=0; $ii<@age; $ii++ )
  40. {
  41.  
  42. for ($jj=0; $jj<@capacitance; $jj++ )
  43. {
  44.  
  45. #$hehe=<STDIN>;
  46.  
  47. $diry= $dir."/".$entradaxx."/".$agingtypex[$iii]."/".$age[$ii].'y'."/".$capacitance[$jj].'_nf/';
  48. #print $diry.'soy  jaja'."\n";
  49.  
  50. chdir($diry)|| die ('It couldnt be:'.$diry.$!."\n");
  51.  
  52.  
  53.  
  54. #print 'jeje'."\n";
  55.  
  56.  
  57. for ($i=0; $i<@lista; $i++ )
  58. {
  59.  
  60. $dirz= $lista[$i].'.aex';
  61. #$dirz= 'prueba.aex';
  62.  
  63. open (PAGE ,"$dirz")|| die ('It couldnt be open:'.$dirz.$!."\n");
  64. @arrayentrada=<PAGE>;
  65.  
  66. open (FILE_OUT ,">>".$lsfout_high)|| die ('It couldnt be open:'.$!."\n");
  67.  
  68.  
  69. for ($j=0; $j<@arrayentrada; $j++ )
  70. {
  71.        
  72.        if($arrayentrada[$j]=~ m/EXTRACT SWEEP/)
  73.          {
  74.          $data0=$arrayentrada[$j];
  75.          
  76.          }
  77.        
  78.         if ($arrayentrada[$j]=~ m/"SETUPTIME_DATA_HIGH"/)
  79.         {
  80.          
  81.          $data2=$arrayentrada[$j];
  82.          #print  $data2;
  83.         }
  84.  
  85.         if ($arrayentrada[$j]=~ m/SETUP_130PS/)
  86.         {
  87.          $data3=$arrayentrada[$j];
  88.           print FILE_OUT  $data3."\n";
  89.          
  90.         }
  91.        
  92.         if ($arrayentrada[$j]=~ m/SETUP_120PS/)
  93.         {
  94.          $data4=$arrayentrada[$j];
  95.         # print  $data4;
  96.         }
  97.        
  98.         if ($arrayentrada[$j]=~ m/SETUP_110PS/)
  99.         {
  100.          $data5=$arrayentrada[$j];
  101.          #print  $data5;
  102.         }
  103.  
  104.  
  105.        if ($arrayentrada[$j]=~ m/SETUP_100PS/)
  106.         {
  107.          $data6=$arrayentrada[$j];
  108.          #print  $data6;
  109.         }
  110.  
  111.        if ($arrayentrada[$j]=~ m/SETUP_90PS/)
  112.         {
  113.          $data7=$arrayentrada[$j];
  114.          #print  $data7;
  115.         }
  116.        
  117.         if ($arrayentrada[$j]=~ m/SETUP_80PS/)
  118.         {
  119.          $data8=$arrayentrada[$j];
  120.          #print  $data8;
  121.         }
  122.  
  123.  
  124.        if ($arrayentrada[$j]=~ m/SETUP_70PS/)
  125.         {
  126.          $data9=$arrayentrada[$j];
  127.          #print  $data9;
  128.         }
  129.  
  130.        if ($arrayentrada[$j]=~ m/SETUP_60PS/)
  131.         {
  132.          $data10=$arrayentrada[$j];
  133.         # print  $data10;
  134.         }
  135.        
  136.         if ($arrayentrada[$j]=~ m/"CLKTOQ_SETUP_130ps"/)
  137.         {
  138.          $data11=$arrayentrada[$j];
  139.         # print  $data11;
  140.         }
  141.         if ($arrayentrada[$j]=~ m/"CLKTOQ_SETUP_120ps"/)
  142.         {
  143.          $data12=$arrayentrada[$j];
  144.         # print  $data12;
  145.         }
  146.         if ($arrayentrada[$j]=~ m/"CLKTOQ_SETUP_110ps"/)
  147.         {
  148.          $data13=$arrayentrada[$j];
  149.          #print  $data13;
  150.         }
  151.        
  152.         if ($arrayentrada[$j]=~ m/"CLKTOQ_SETUP_100ps"/)
  153.         {
  154.          $data14=$arrayentrada[$j];
  155.          #print  $data14;
  156.         }
  157.        
  158.         if ($arrayentrada[$j]=~ m/"CLKTOQ_SETUP_90ps"/)
  159.         {
  160.          $data15=$arrayentrada[$j];
  161.          #print  $data15;
  162.         }
  163.        
  164.         if ($arrayentrada[$j]=~ m/"CLKTOQ_SETUP_80ps"/)
  165.         {
  166.          $data16=$arrayentrada[$j];
  167.          #print  $data16;
  168.         }
  169.         if ($arrayentrada[$j]=~ m/"CLKTOQ_SETUP_70ps"/)
  170.         {
  171.          $data17=$arrayentrada[$j];
  172.         # print  $data17;
  173.         }
  174.         if ($arrayentrada[$j]=~ m/"CLKTOQ_SETUP_60ps"/)
  175.         {
  176.          $data18=$arrayentrada[$j];
  177.          #print  $data18;
  178.         }
  179.  
  180.  
  181.  
  182. }#arrayentrada
  183.  
  184.  
  185.  
  186. format FILE_OUT =
  187.           name:@<<<<<<<<<<<   @<<<<<<<   @<<<<<<<     @<<<<<<<           @<<<<<<<<           @<<<<<<<<      @<<<<<<<<  @<<<<<<<     @<<<<<   @<<<<<<<
  188.                 $name[8],     $Vstress,  $age[$ii],   $agingtypex[$iii],  $capacitance[$jj],  $lista1,    $HOLD[0],  $SETUP[2],  $data3,   $data11
  189.                 $name[8],     $Vstress,  $age[$ii],   $agingtypex[$iii],  $capacitance[$jj],  $lista[$i],    $HOLD[1],  $SETUP[3],  $data4,   $data12
  190. .
  191. #$hehe=<STDIN>;
  192. #print FILE_OUT;
  193. write FILE_OUT;
  194.  
  195.  
  196. }#lista
  197. }#for capacitance
  198. #print 'jojo'."\n";
  199. }
  200. }
  201.  
  202.  
  203. }#;first if
  204.  
  205. }#first for
  206. close PAGE;
  207. close FILE_OUT;
Coloreado en 0.006 segundos, usando GeSHi 1.0.8.4
STM
Perlero nuevo
Perlero nuevo
 
Mensajes: 23
Registrado: 2008-07-01 07:12 @342

Publicidad

Re: Problema para imprimir en archivo

Notapor explorer » 2010-08-03 06:05 @295

Si Perl ve un error en el momento de abrir un fichero, debe decírtelo en la variable $!, pero no nos muestras qué error sale, así que no sabemos qué puede pasar.

Una cosa mal que has hecho es comentar la línea 2. 'strict' es tu mejor amigo. Te obligará a declarar todas las variables que haya en tu programa. Eso te ayudará a encontrar variables mal escritas, duplicadas o que no se usen nunca.

Otro detalle: no es necesario meter la definición del formato FILE_OUT dentro de un bucle. Basta con que lo tengas definido fuera, en otro sitio.

En el tema del if(), lo que ocurre es que la variable a la que accedes no tiene ningún valor (o dicho de otra manera, su valor es indefinido). Eso puede ocurrir porque no se hayan dado todas las circunstancias de todos los if() posibles, y queden algunas variables sin inicializar.

Aquí tienes otro problema: como estás usando variables globales, los valores de una línea pasan a la siguiente. Puedes tener duplicidades.

Esta es una versión un poco más limpia. No lo he podido ejecutar, porque no tengo claro cómo son los ficheros a leer. Sintácticamente, ha pasado la prueba del precompilado (perl -c fichero.pl), pero ya se observa que hay alguna variable que "sobra", o que no se utiliza, como el caso de @agingtype.
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. use diagnostics;
  5.  
  6. use Cwd;
  7.  
  8. my $dir     = getcwd;                # directorio actual
  9. my $Vstress = '1.32';                # versión
  10. my @name    = split( /\//, $dir );
  11. my @entrada = ( 1 .. 2 );
  12. my @HOLD    = ( 1 .. 5 );
  13. my @SETUP   = ( 22 .. 25 );
  14.  
  15. my @data;
  16. my $age;
  17. my $agingtypex;
  18. my $capacitance;
  19.  
  20. ##################
  21. my @lista = ( 'zoneA', 'zoneB', 'SP0', 'SP50', 'SP100' );
  22. my @age = ( '2', '0.2', '0.02' );
  23. #my @agingtype   = ( 'hci=0 nbti=1', 'hci=1 nbti=0', 'hci=1 nbti=1' );
  24. my @agingtypex  = ( 'nbti',       'hci',        'NBTI+HCI' );
  25. my @capacitance = ( '0.0008e-12', '0.0141e-12', '0.0495e-12' );
  26. my $lsfout_high = 'extract.cvs';
  27. my $lista1      = '12';
  28. $data[3]  = '87';
  29. $data[11] = '87';
  30. ############
  31.  
  32. #########
  33. for my $entrada (@entrada) {
  34.  
  35.     if ( $entrada == 1 ) {
  36.         my $entrada   = "$dir/charac_CSHT_Fresh_high.cir";
  37.         my $entradaxx = 'charac_DATA_high';
  38.  
  39.         for $agingtypex (@agingtypex) {
  40.  
  41.             for $age (@age) {
  42.  
  43.                 for $capacitance (@capacitance) {
  44.  
  45.                     my $diry
  46.                         = join q[/],
  47.                             $dir, $entradaxx, $agingtypex, "${age}y", "${capacitance}_nf/";
  48.  
  49.                     chdir($diry)
  50.                         or die( 'It couldnt be:' . $diry . $! . "\n" );
  51.  
  52.                     for my $i ( 0 .. $#lista ) {
  53.  
  54.                         my $dirz = $lista[$i] . '.aex';
  55.  
  56.                         #$dirz= 'prueba.aex';
  57.  
  58.                         open( PAGE, "$dirz" )
  59.                             or die "It couldnt be open: $dirz: $!\n";
  60.  
  61.                         my @fichero = <PAGE>;
  62.  
  63.                         open( FILE_OUT, ">>" . $lsfout_high )
  64.                             or die "It couldnt be open $lsfout_high: $!\n";
  65.  
  66.                         for my $linea (@fichero) {
  67.  
  68.                             if ( $linea =~ m/EXTRACT SWEEP/ ) {
  69.                                 $data[0] = $linea;
  70.                             }
  71.  
  72.                             if ( $linea =~ m/"SETUPTIME_DATA_HIGH"/ ) {
  73.                                 $data[2] = $linea;
  74.                             }
  75.  
  76.                             if ( $linea =~ m/SETUP_130PS/ ) {
  77.                                 $data[3] = $linea;
  78.                                 print FILE_OUT $data[3] . "\n";
  79.                             }
  80.  
  81.                             if ( $linea =~ m/SETUP_120PS/ ) {
  82.                                 $data[4] = $linea;
  83.                             }
  84.  
  85.                             if ( $linea =~ m/SETUP_110PS/ ) {
  86.                                 $data[5] = $linea;
  87.                             }
  88.  
  89.                             if ( $linea =~ m/SETUP_100PS/ ) {
  90.                                 $data[6] = $linea;
  91.                             }
  92.  
  93.                             if ( $linea =~ m/SETUP_90PS/ ) {
  94.                                 $data[7] = $linea;
  95.                             }
  96.  
  97.                             if ( $linea =~ m/SETUP_80PS/ ) {
  98.                                 $data[8] = $linea;
  99.                             }
  100.  
  101.                             if ( $linea =~ m/SETUP_70PS/ ) {
  102.                                 $data[9] = $linea;
  103.                             }
  104.  
  105.                             if ( $linea =~ m/SETUP_60PS/ ) {
  106.                                 $data[10] = $linea;
  107.                             }
  108.  
  109.                             if ( $linea =~ m/"CLKTOQ_SETUP_130ps"/ ) {
  110.                                 $data[11] = $linea;
  111.                             }
  112.                             if ( $linea =~ m/"CLKTOQ_SETUP_120ps"/ ) {
  113.                                 $data[12] = $linea;
  114.                             }
  115.                             if ( $linea =~ m/"CLKTOQ_SETUP_110ps"/ ) {
  116.                                 $data[13] = $linea;
  117.                             }
  118.  
  119.                             if ( $linea =~ m/"CLKTOQ_SETUP_100ps"/ ) {
  120.                                 $data[14] = $linea;
  121.                             }
  122.  
  123.                             if ( $linea =~ m/"CLKTOQ_SETUP_90ps"/ ) {
  124.                                 $data[15] = $linea;
  125.                             }
  126.  
  127.                             if ( $linea =~ m/"CLKTOQ_SETUP_80ps"/ ) {
  128.                                 $data[16] = $linea;
  129.                             }
  130.                             if ( $linea =~ m/"CLKTOQ_SETUP_70ps"/ ) {
  131.                                 $data[17] = $linea;
  132.                             }
  133.                             if ( $linea =~ m/"CLKTOQ_SETUP_60ps"/ ) {
  134.                                 $data[18] = $linea;
  135.                             }
  136.  
  137.                         }    #linea
  138.  
  139.                         write FILE_OUT;
  140.  
  141.                     }    #lista
  142.                 }    #for capacitance
  143.             }
  144.         }
  145.     }    #;first if
  146. }    #first for
  147.  
  148. close PAGE;
  149. close FILE_OUT;
  150.  
  151. format FILE_OUT =
  152.           name:@<<<<<<<<<<<   @<<<<<<<   @<<<<<<<     @<<<<<<<           @<<<<<<<<           @<<<<<<<<      @<<<<<<<<  @<<<<<<<     @<<<<<   @<<<<<<<
  153.                 $name[8],     $Vstress,  $age,        $agingtypex,  $capacitance,  $lista1,      $HOLD[0],  $SETUP[2],  $data[3], $data[11]
  154.                 $name[8],     $Vstress,  $age,        $agingtypex,  $capacitance,  $lista[$i],   $HOLD[1],  $SETUP[3],  $data[4], $data[12]
  155. .
  156.  
Coloreado en 0.005 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

Recuperar el valor de una variable e imprimirlo en un format

Notapor STM » 2010-08-03 09:52 @453

Hola explorer, gracias por la respuesta.

Ahora quisiera hacerle otra pregunta pero esta vez es con respecto a la aplicabilidad de la función "format".

En mi archivo de entrada yo tengo varios index "nnn"

Sintáxis: [ Descargar ] [ Ocultar ]
Using text Syntax Highlighting
index 0
    *SETUP_130PS = -2.8480E-02  
    *SETUP_120PS = -2.6843E-02  
    *SETUP_110PS =  1.2362E-03  
    *SETUP_100PS =  2.1223E-02  
    *SETUP_90PS =  2.3898E-02  
    *SETUP_80PS =  3.2453E-04  
    *SETUP_70PS = -3.6209E-02  
    *SETUP_60PS =  1.3664E-01  
Coloreado en 0.000 segundos, usando GeSHi 1.0.8.4


y yo quisiera hacer una tabla de esta manera:

Sintáxis: [ Descargar ] [ Ocultar ]
Using text Syntax Highlighting
INDEX    SETUP
0         setup_130
.
.
.
0         setup_600
.
.
.
25        setup_130
.
.
.         setup_60ps
25  
Coloreado en 0.000 segundos, usando GeSHi 1.0.8.4


Y la verdad la única manera que se me ocurrió para detectar el patrón fue:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
for{arrayentrada[$j]
    if (=~m/setup_130ps/)
        {$_= $data1}
}
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4


pero fuera del if(), $data1 no es conocida, así que cuando trato de imprimir el valor de $data1 en mi formato Perl genera un error porque la variable no ha sido inicializada.

¿Podría indicarme cómo recuperar el valor de $data1 para poder luego imprimirlo?

Gracias de antemano
STM
Perlero nuevo
Perlero nuevo
 
Mensajes: 23
Registrado: 2008-07-01 07:12 @342

Re: Problema para imprimir en archivo

Notapor explorer » 2010-08-03 11:22 @515

Si $data1 no tiene un valor, es porque nunca ha pasado por el if().

¿Puedes indicarnos qué versión de Perl estás usando?

¿Puedes poner un ejemplo de salida completo? -recortando líneas para que salga muy largo-. Es que no me queda claro lo que has puesto de fichero de salida...

He visto que has puesto un ejemplo de fichero de entrada, así que supongo que todos son así.
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: Problema para imprimir en archivo

Notapor explorer » 2010-08-03 12:20 @555

Según lo indicado, aquí tienes un ejemplo.

Supongamos que tenemos dos ficheros: index0.txt e index25.txt. El número indicado en el nombre será el número que pongamos en la primera columna (parecido a como lo tienes en tu programa). Cada uno de ellos contiene lo mismo que lo indicado en el fichero de entrada de ejemplo.

Entonces, con el programa
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. #!/usr/bin/perl
  2. use 5.010;
  3. use strict;
  4. use warnings;
  5. use diagnostics;
  6.  
  7. open my $SALIDA, q[>>], 'salida.txt';
  8. print $SALIDA "INDEX    SETUP\n";
  9.  
  10. for my $fichero (<index*.txt>) {
  11.  
  12.     my($indice) = $fichero =~ /(\d+)/;      # buscamos una cifra en el nombre del fichero
  13.  
  14.     open my $PAGE, q[<], $fichero  or  die "ERROR: no puedo leer $fichero: $!\n";
  15.    
  16.     for (<$PAGE>) {
  17.         when (/(SETUP_\d+PS)/) {
  18.             printf $SALIDA "%-8s %-12s\n", $indice, $1;
  19.         }
  20.     }
  21.  
  22.     close $PAGE;
  23. }
  24.  
  25. close $SALIDA;
  26.  
  27. __END__
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4
entonces en el fichero de salida se ha grabado
Sintáxis: [ Descargar ] [ Ocultar ]
Using text Syntax Highlighting
INDEX    SETUP
0        SETUP_130PS
0        SETUP_120PS
0        SETUP_110PS
0        SETUP_100PS
0        SETUP_90PS  
0        SETUP_80PS  
0        SETUP_70PS  
0        SETUP_60PS  
25       SETUP_130PS
25       SETUP_120PS
25       SETUP_110PS
25       SETUP_100PS
25       SETUP_90PS  
25       SETUP_80PS  
25       SETUP_70PS  
25       SETUP_60PS  
Coloreado en 0.000 segundos, usando GeSHi 1.0.8.4

En resumen, lo que hace el programa es:
* abrimos el fichero de salida, en modo añadir
* escribimos una cabecera
* por cada fichero index* encontrado...
* analizamos línea a línea
* por cada línea, si coincide con el patrón buscado
* sacamos la nueva línea al fichero de salida, formateado con printf()
* cerramos fichero
* cerramos fichero de salida

El código está escrito para Perl v5.10.
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


Volver a Básico

¿Quién está conectado?

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

cron