• Publicidad

Consulta sobre || y or

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

Consulta sobre || y or

Notapor pablgonz » 2012-01-17 11:23 @516

Estimados amigos del foro: he escrito un script basado en otro que ya conocía bastante bien y sabía cómo funcionaba. Al modificar y eliminar líneas me percaté de que habían varios || y no recuerdo si lo leí en el foro en algún tutorial en la red, que era preferible usar «or» en su lugar.

¿Es correcto esto?

Gracias por todo
Pablo
pablgonz
Perlero nuevo
Perlero nuevo
 
Mensajes: 236
Registrado: 2010-09-08 21:03 @919
Ubicación: Concepción (Chile)

Publicidad

Re: Consulta sobre || y or

Notapor explorer » 2012-01-17 11:43 @529

La diferencia entre los dos es solo su precedencia.

Eso quiere decir que en esta situación:

EXPRESIÓN op EXPRESIÓN || EXPRESIÓN op EXPRESIÓN

se ejecutará así:

EXPRESIÓN op (EXPRESIÓN || EXPRESIÓN) op EXPRESIÓN

mientras que con

EXPRESIÓN op EXPRESIÓN or EXPRESIÓN op EXPRESIÓN

se ejecutará así:

(EXPRESIÓN op EXPRESIÓN) or (EXPRESIÓN op EXPRESIÓN)

Bueno, esto está explicado de forma un poco burda, porque también depende de la precedencia de 'op' (otro operador).

Tienes la lista de precedencia al principio del documento perlop.

Es preferible usar 'or', porque tiene una precedencia muy baja, así que sabemos que será de los últimos operadores que se ejecuten en la sentencia. Así, podemos escribir cosas como esta sin tener que poner paréntesis:

Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
if ($linea == 23  or  $linea == 24) {
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

Re: Consulta sobre || y or

Notapor pablgonz » 2012-01-17 11:58 @540

Gracias por la aclaración, supongo que en situaciones como esta también es valido (y preferible) cambiar
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. mkdir("$imageDir", 0744) || die "cannot mkdir $imageDir: $!";
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4
por
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. mkdir("$imageDir", 0744) or die "cannot mkdir $imageDir: $!";
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4
pablgonz
Perlero nuevo
Perlero nuevo
 
Mensajes: 236
Registrado: 2010-09-08 21:03 @919
Ubicación: Concepción (Chile)

Re: Consulta sobre || y or

Notapor explorer » 2012-01-17 12:06 @546

Pues sí, por seguridad (en el sentido de que no sabemos si esa línea la vamos a cambiar en el futuro, y al hacer ese cambio, el '||' hará de las suyas).

En el caso concreto que pones, además, lo más moderno es ni siquiera poner el die(). Como se trata de una operación con ficheros, es mejor que lo gestione autodie:

Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. use autodie;               # "Es mejor morir que regresar con deshonor --Proverbio Kinglon"
  2.  
  3. mkdir $imageDir, 0744;
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4

Queda mucho más corto, ¿verdad? :)
Ejemplo:
Sintáxis: [ Descargar ] [ Ocultar ]
Using bash Syntax Highlighting
  1. explorer@casa:~/Documentos/Desarrollo> perl -E 'use autodie; mkdir "/kkk", 0755;'
  2. Can't mkdir('/kkk', '493'): Permiso denegado at -e line 1
  3.  
Coloreado en 0.004 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: Consulta sobre || y or

Notapor pablgonz » 2012-01-17 12:22 @557

Tienes toda la razón, no conocía autodie. El tema es que tengo dentro del script varias veces "or die", te muestro el código:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. eval '(exit $?0)' && eval 'exec perl -S $0 ${1+"$@"}' && eval 'exec perl -S $0 $argv:q'
  2.   if 0;
  3.  
  4. use strict;                             # to be sure, that all is safe ... :-)
  5.  
  6. # $Id: tikz2pdf.pl 2012-01-17 08:41:35Z Pablo $
  7. # v. 0.1                                Extract tikzpicture, based on pst2pdf by Herbert Voss
  8. # 2012-01-17      (c) Pablo González Luengo
  9. # Thanks to Giuseppe Matarazzo.
  10. # Couple to have the complete operation of the script, you need some software (Linux and Windows)
  11. # xpdf (needed to create EPS / PPM)
  12. # gnuplot (not necessary if not called from TiKZ)
  13. # pdftk (not necessary with the-pdftk)
  14. # ImageMagick (required if you want to create JPG / PNG or other format)
  15. #      
  16. use File::Path;  
  17. use File::Copy;  
  18. use File::Basename;    
  19. use IO::File;      
  20. use Getopt::Long;              
  21. #----------------------- User part begin ------------------------
  22. my $imageDir = "images";       
  23. my $Iext = ".pdf";                      # leave empty, if not a special one
  24. my $tempDir = ".";                      # temporary directory
  25. my $verbose = 1;                          # 0 or 1, logfile  
  26. my $clear = 0;                            # 0 or 1, clears all temporary files
  27. my $DPI = 75;                               # very low value for the png's
  28. my $Iscale = 1;                           # for \includegraphics
  29. my $noImages = 0;                         # 1->create no images
  30. my $force = 0;                  # 1->force create images
  31. my $ppm = 0;                            # 1->create .ppm files
  32. my $norun = 0;                          # 1->runs pdflatex
  33. my $miktex = 0;                         # 1->runs pdlatex for miktex
  34. my $eps = 0;                            # 1->create .eps files
  35. my $ifiles = 0;                         # 1->create image files .tex
  36. my $all = 0;                            # 1->create all images and files for type
  37. my $nopdftk = 0;                                # 1->create all images and files for type in force mode
  38. #----------------------- User part end ---------------------------
  39. #----------------------- program identification, options and help
  40. my $program = "tikz2pdf";
  41. my $ident = '$Id: tikz2pdf.pl 2012-01-17 pablo $';
  42. my $copyright = <<END_COPYRIGHT ;
  43. Copyright 2012-01-17 (c) Pablo Gonzalez L <pablgonz\@yahoo.com>
  44. END_COPYRIGHT
  45. my $licensetxt= <<END_LICENSE ;
  46.     This program is free software; you can redistribute it and/or modify
  47.     it under the terms of the GNU General Public License as published by
  48.     the Free Software Foundation; either version 2 of the License, or
  49.     (at your option) any later version.
  50.  
  51.     This program is distributed in the hope that it will be useful, but
  52.     WITHOUT ANY WARRANTY; without even the implied warranty of
  53.     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  54.     General Public License for more details.
  55.  
  56.     You should have received a copy of the GNU General Public License
  57.     along with this program; if not, write to the Free Software
  58.     Foundation, Inc., 59 Temple Place, Suite 330, Boston,
  59.     MA  02111-1307  USA
  60. END_LICENSE
  61. my $title = "$program $ident\n";
  62. my $usage = <<"END_OF_USAGE";
  63. ${title}Usage: $program <texfile.tex>  [Options]
  64. tikz2pdf run a TeX source, and extract all TiKZ-related part as
  65.         single images  (pdf or eps or ppm, default pdf)
  66.         and then runs pdflatex. See tikz2pdf documentation for more info
  67. Options:
  68.   --help          - display this help and exit
  69.   --version       - display version information and exit
  70.   --license       - display license information and exit
  71.   --imageDir      - the dir for the created images (default images)
  72.   --DPI=<int>     - the dots per inch for a cretaed ppm files (default 75)
  73.   --ppm           - create .ppm files
  74.   --eps           - create .eps files  
  75.   --Iscale=<real> - the value for [scale=] in \\includegraphics
  76.   --noImages      - generate files without compile (need -norun)
  77.   --verbose       - creates long log
  78.   --clear         - delete all temp files
  79.   --norun         - create file-pdf.tex, but, no run pdflatex
  80.   --miktex        - for miktex users -enable-write18
  81.   --ifiles        - create images files (.tex) for all TiKZ enviroment 
  82.   --force         - create images whitout pdftk.
  83.   --all           - create all image type and images.tex       
  84.   --nopdftk          - create all image type and images.tex in force mode
  85. Examples:
  86. * $program test.tex --all
  87. * produce test-pdf.tex and ppm,eps,tex and pdf for TiKZ-enviroment in image dir
  88. END_OF_USAGE
  89. #
  90. my $result=GetOptions (
  91.                         "help",
  92.                         "version",
  93.                         "license",
  94.                         "DPI=i"      => \$DPI,          # numeric
  95.                         "Iscale=f"   => \$Iscale,       # real
  96.                         "imageDir=s" => \$imageDir,     # string
  97.                         "tempDir=s"  => \$tempDir,      # string
  98.                         "Iext=s"     => \$Iext,         # string
  99.                         "clear"      => \$clear,        # flag
  100.                         "noImages"   => \$noImages,     # flag
  101.                         "force"      => \$force,        # flag
  102.                         "ppm"        => \$ppm,         # flag
  103.                         "norun"      => \$norun,       # flag
  104.                         "miktex"     => \$miktex,      # flag
  105.                         "eps"        => \$eps,          # flag
  106.                         "ifiles"        => \$ifiles,            # flag
  107.                         "all"        => \$all,          # flag
  108.                         "nopdftk"        => \$nopdftk,          # flag
  109.                         "verbose"    => \$verbose,
  110. ) or die $usage;
  111. # help functions
  112. sub errorUsage { die "Error: @_ (try --help for more information)\n"; }
  113. # options for command line
  114. if ($::opt_help) {
  115.   print $usage;
  116.   exit (0);
  117. }
  118. if ($::opt_version) {
  119.   print $title;
  120.   print $copyright;
  121.   exit (0);
  122. }
  123. if ($::opt_license) {
  124.   print $licensetxt;
  125.   exit (0);
  126. }
  127. # open file
  128. my $InputFilename = "";
  129.   @ARGV > 0 or errorUsage "Input filename missing";
  130.   @ARGV < 2 or errorUsage "Unknown option or too many input files";
  131.   $InputFilename = $ARGV[0];
  132. # end open file
  133. my @SuffixList = (".tex","",".ltx");            # possible extensions
  134. my ($name,$path,$ext) = fileparse($ARGV[0],@SuffixList);
  135. if ($ext eq "") { $ext = ".tex"; }                      # me need the extension as well
  136. my $TeXfile = "$path$name$ext";
  137. my $Logfile = "$tempDir/$name.plog";            # our own log file
  138. open (LOGfile,">$Logfile") or die "cannot open $Logfile!";
  139. LOG ("Parameters:");
  140. LOG ("==> imageDir = $imageDir");
  141. LOG ("==> Iext     = $Iext");
  142. LOG ("==> DPI      = $DPI");
  143. LOG ("==> Iscale   = $Iscale");
  144. LOG ("==> tempDir  = $tempDir");
  145. LOG ("==> verbose  = $verbose");
  146. LOG ("==> clear    = $clear");
  147. LOG ("==> noImages = $noImages");
  148. LOG ("==> force    = $force");
  149. LOG ("==> ppm      = $ppm");
  150. LOG ("==> norun    = $norun");
  151. LOG ("==> miktex   = $miktex");
  152. LOG ("==> eps      = $eps");  
  153. LOG ("==> ifiles   = $ifiles");
  154. # General options
  155. if ($ppm) {
  156.   LOG ("Generate .ppm files ...");
  157.   $ppm = 1;
  158. }
  159. if ($norun) {
  160.   LOG ("no compile file-pdf.tex");
  161.   $norun = 1;
  162. }
  163. if ($miktex) {
  164.   LOG ("enable write 18 ...");
  165.   $miktex = 1;
  166. }
  167. if ($eps) {
  168.   LOG ("Generate .eps files ...");
  169.   $eps = 1;
  170. }
  171. if ($ifiles) {
  172.   LOG ("Generate .tex images files ...");
  173.   $ifiles=1;
  174. }
  175. if ($all) {
  176.   LOG ("Generate all images files ...");
  177.    $ifiles=$eps = $ppm = $clear = 1;
  178. }
  179. if ($nopdftk) {
  180.   LOG ("Forced generate all images files ...");
  181.   $force=$ifiles=$eps = $ppm = $clear = 1;
  182. }
  183. # Internal counter
  184. my $imgNo = 1;         
  185. # force mode , compile separte files
  186. if ($force) {
  187. LOG ("Running on [$path][$name][$ext]");
  188. open (FILE, "<$TeXfile") or die "cannot open source file $TeXfile!";
  189. LOG ("force generate images...");
  190. if (-d $imageDir) { LOG ("$imageDir exists") }
  191. else { mkdir("$imageDir", 0744) or die "cannot mkdir $imageDir: $!";}
  192. savePreamble($name);
  193. runFile($name);
  194. close FILE;                            
  195. close LOGfile;
  196. }
  197. else{
  198. LOG ("Running on [$path][$name][$ext]");
  199. open (FILE, "<$TeXfile") or die "cannot open source file $TeXfile!";   
  200. if (!$noImages ) {
  201. if (-d $imageDir) { LOG ("$imageDir exists") }
  202. else {
  203. mkdir("$imageDir", 0744) or die "cannot mkdir $imageDir: $!";
  204. LOG ("Imagedir created"); }
  205. LOG ("go to savePreamble ... ");
  206. runBurst($tempDir);
  207. savePreamble($name);
  208. runFile($name);
  209. LOG ("done!\n go to runFile ...");
  210. LOG ("done!");
  211. close FILE;                                    
  212. close LOGfile;
  213. }
  214. }
  215. #------------ Create filename-pics.pdf, split and generate .ppm
  216. sub runBurst{
  217. if ($force){ print "Force mode";}
  218. else{
  219. # Append preview
  220. my $entrada="$TeXfile";
  221. my $salida ="$name-pics.tex";
  222. open (ENTRADA,"<$entrada");
  223. open (SALIDA,">$salida") ;
  224.  print SALIDA "\\AtBeginDocument\{\n";
  225.  print SALIDA "\\RequirePackage\[active,tightpage\]\{preview\}\n";
  226.  print SALIDA "\\renewcommand\\PreviewBbAdjust\{-600pt -600pt 600pt 600pt\}\n";
  227.  print SALIDA "\\PreviewEnvironment\{tikzpicture\}\}\n";
  228.  while (my $linea=<ENTRADA>)
  229.   {
  230.         print SALIDA $linea;
  231.   }
  232. close (ENTRADA);
  233. close (SALIDA);
  234. # close preview
  235.  
  236. if ($miktex){system("pdflatex -enable-write18 -interaction=batchmode $name");}
  237. else{
  238. system("pdflatex -shell-escape -interaction=batchmode $tempDir/$name-pics.tex");
  239. system("pdfcrop $tempDir/$name-pics.pdf $tempDir/$name-pics.pdf");
  240. system("pdftk $name-pics.pdf burst output $imageDir/$name-tikz-\%1d.pdf");
  241. }
  242. if ($ppm){
  243. system("pdftoppm -r  $DPI $name-pics.pdf $imageDir/$name-tikz");
  244. }
  245. }
  246. }
  247. #------------ end pdftk burst
  248. LOG ("runpdfTeX ... ");
  249. runpdfTeX("$path$name",$name);
  250. LOG ("all finished ... :-)");
  251. if ( $clear ) {
  252. unlink "$path$name.txt";
  253. unlink "$path$name.log";
  254. unlink "$path$name.plog";
  255. unlink "$path$name.preamble";
  256. unlink "$path$name.pdf";
  257.  }
  258. # Save preable
  259. sub savePreamble {                             
  260.   my $filename = pop;
  261.   LOG ("----- Start Preamble -----");
  262.   open (FILEp, ">$tempDir/$filename.preamble")
  263.     or die "cannot open preamble file $tempDir/$filename.preamble!";
  264.   while (<FILE>) {             
  265.     my $i = index($_,"begin{document}");
  266.     if ($i > 0) {
  267.       if ($i > 1) { print FILEp substr($_,0,--$i); }   
  268.                         if ($force) {
  269.                         print FILEp "\\pagestyle{empty}\n";
  270.                         }
  271.       close(FILEp);
  272.       LOG ("----- Close Preamble ------");
  273.       return;
  274.     } else {
  275.       print FILEp "$_";
  276.       LOG ("$_");
  277.     }
  278.   }
  279.   close(FILEp);
  280.   if ( $verbose ) { LOG("<-----Preamble<----"); }
  281.   return;
  282. }
  283.  
  284. sub searchTiKZ {                                       
  285.   my @TikZ = ();                                       
  286.   my @TIKZtotal = ();                  
  287.   my $depth = -1;                                      
  288.   my $type = -1;                                       
  289.   my $EndDocument = 0;         
  290.   my $iVerb = 0;                                       
  291.   while (<FILE>) {                             
  292.     if (!$EndDocument) {
  293.     chomp;                                                       
  294.     my $line = $_;                             
  295.     if ( !$iVerb ) {
  296.       $iVerb = ((index($line,"begin{verbatim}") > 0) or (index($line,"begin{lstlisting}") > 0));
  297.     }          
  298.     if ( !$iVerb ) {
  299.       my $iTIKZ = index($line,"begin{tikzpicture}");
  300.        if ( $type < 0 ) {                      
  301.       if ($iTIKZ > 0) {                        
  302.           $type = 2;                   
  303.           $line = substr($line,$iTIKZ-1);      
  304.           LOG("TiKZ-line: $line");
  305.         }                              
  306.        }
  307.  
  308. if ($type > 0) {
  309.         LOG ("searchTiKZ: set \$type=$type");
  310.         $iTIKZ = index($line,"end{tikzpicture}");      
  311.         if ($iTIKZ > 0) {              
  312.           LOG ("searchTiKZ: $line");
  313.                                 $type = -1;
  314.           push @TikZ,substr($line,0,$iTIKZ+16);
  315.           LOG ("searchTiKZ: set \$type=$type");
  316.           push @TIKZtotal,[@TikZ];                     
  317.           LOG ("---->TiKZ---->\n@TikZ\n<----TikZ<----");
  318.           @TikZ =();                   
  319.         } else { push @TikZ,$line; }    # add line
  320.       }
  321.       my $i = index($line,"end{document}");
  322.       if ($i > 0) { $EndDocument++; LOG("EndDocument in searchTiKZ"); }
  323.     }                  
  324.     if (( index($line,"end{verbatim}") > 0 ) or ( index($line,"end{lstlisting}") > 0 )) { $iVerb = 0; }
  325.   }}
  326.   if ( $verbose ) {
  327.     LOG("---->TIKZtotal---->");
  328.     for my $aref ( @TIKZtotal ) {
  329.       my @a = @$aref;
  330.       my $i = 1;
  331.                         foreach ( @a ) { LOG ($a[$i]); $i=$i+1; }
  332.     }
  333.     LOG ("<----TIKZtotal<----");
  334.   }
  335.   close(FILE);
  336.   return @TIKZtotal;   
  337. }
  338. # Creating ifile.tex and eps, pdf and ppm for images
  339. if ($force){
  340. sub runFORCE{
  341. my $filename = pop;
  342. if ($miktex){system("pdflatex -enable-write18 -interaction=batchmode $tempDir/$filename-tikz");}
  343. else{system("pdflatex -interaction=batchmode $tempDir/$filename-tikz");}
  344. if ($ifiles){
  345. copy("$filename-tikz.tex", "$imageDir/$filename-tikz-$imgNo.tex") or die "Cannot copy Source file!";
  346. }
  347. system("pdfcrop $tempDir/$filename-tikz.pdf $imageDir/$filename-tikz-$imgNo.pdf");  
  348. if ($eps) {system("pdftops -level3 -eps $imageDir/$filename-tikz-$imgNo.pdf $imageDir/$filename-tikz-$imgNo.eps");}
  349. if ($ppm) {system("pdftoppm -r $DPI $imageDir/$filename-tikz-$imgNo.pdf $imageDir/$filename-tikz-$imgNo");}
  350.     $imgNo=$imgNo+1;
  351.         }
  352. }
  353. else{
  354. # Creating ifiles.tex and .eps for images
  355. sub runTeX{
  356. my $filename = pop;
  357. if ($eps){
  358.                         system("pdftops -level3 -eps $imageDir/$filename-$imgNo.pdf $imageDir/$filename-$imgNo.eps");
  359.                    }
  360. if ($ifiles){
  361. copy("$filename.tex", "$imageDir/$filename-$imgNo.tex") or die "Cannot copy Source file!";
  362. }
  363. $imgNo=$imgNo+1;
  364. }
  365. }
  366. sub runFile {
  367.   my $filename = pop;
  368.   my @TIKZarray = searchTiKZ();
  369.   if ( $verbose ) {
  370.     LOG("---->TIKZarray---->");
  371.     for my $aref ( @TIKZarray ) {
  372.       my @a = @$aref;
  373.       my $i = 1;
  374.       foreach ( @a ) { print LOG $a[$i]."\n"; $i=$i+1; }
  375.     }
  376.     LOG("<----TIKZarray<----");
  377.     my $no = @TIKZarray;
  378.     LOG("TiKZ: ".$no." TiKZ sequence(s)");
  379.   }
  380.   for my $aref ( @TIKZarray ) {
  381.     my @TikZ = @$aref;
  382.     open (FILEp,"<$tempDir/$filename.preamble") or die "cannot open $tempDir/$filename.preamble!";
  383.     open (FILEsub,">$tempDir/$filename-tikz.tex") or die "cannot open $tempDir/$filename-tikz.tex!";
  384.     while (<FILEp>) {print FILEsub $_; }
  385.                 print FILEsub "\\begin{document}\n";
  386.                 if ( $verbose ) { LOG("\@TikZ: $_"); }
  387.     foreach ( @TikZ ) { print FILEsub "$_\n"; }
  388.     print FILEsub "\\end{document}";
  389.     close (FILEsub);
  390.     close (FILEp);
  391.                 if ($force) {
  392.                 runFORCE("$name");
  393.                 }
  394.                 else{
  395.     runTeX("$tempDir/$name-tikz");
  396.   }
  397. }
  398. }
  399. # Renaming ppm need for correct name
  400. my $dren = "$tempDir/$imageDir";
  401. my $fichero = '';
  402. my $ppmren = '';
  403. my $renNo = 1;
  404. if(opendir(DIR,$dren)){
  405. foreach (readdir DIR){
  406.        $fichero = $_;
  407.                         if ( $fichero =~ /($name-tikz-)(\d+|\d+[-]\d+).ppm/) {
  408.         my $renNo   = int($2);
  409.         my $newname="$1$renNo.ppm";
  410.         $ppmren = rename("$dren/$fichero","$dren/$newname");
  411.         }
  412.         }
  413. }
  414. closedir DIR;
  415. # end renaming
  416. # Replace files
  417. sub runpdfTeX() {
  418.   my ($name,$pdfname) = @_;
  419.   open (PDF, ">$tempDir/$pdfname-pdf.tex") or die "cannot open $tempDir/$pdfname-pdf.tex!";
  420.   open (FILE, "<$name.tex") or die "cannot open $name!";
  421.         print PDF "\\RequirePackage{grfext}\n";
  422.         print PDF "\\PrependGraphicsExtensions*{$Iext}\n";
  423.         print PDF "\\RequirePackage{graphicx}\n";
  424.         print PDF "\\graphicspath{{$imageDir/}}\n";
  425.   my $ignore = 0;
  426.   my $IMGno = 1;
  427.   my $depth = -1;
  428.   my $type = -1;
  429.   my $EndDocument = 0;
  430.   my $iVerb = 0;
  431.   while (<FILE>) {
  432.     if ( !$iVerb ) {
  433.       $iVerb = ((index($_,"begin{verbatim}") > 0) or (index($_,"begin{lstlisting}") > 0));
  434.     }
  435.     if ( !$iVerb ) {
  436.       my $i = index($_,"end{document}");
  437.       if ($i > 0) { print PDF $_; $EndDocument++; LOG("EndDocument in runpdfTeX"); }
  438.       if ( !$EndDocument ) {
  439.         my $iTIKZ = index($_,"begin{tikzpicture}");
  440.         if ( $iTIKZ > 0 ) {
  441.           $type = 2;
  442.           $ignore = 1;
  443.           if ($iTIKZ > 1) { print PDF substr($_,0,--$iTIKZ); } 
  444.         print PDF "\\includegraphics[scale=$Iscale]{$pdfname-tikz-$IMGno}";
  445.           $IMGno=$IMGno+1;
  446.         }              
  447.         if ( !$ignore ) { print PDF "$_"; }    
  448.         if ( $type == 2 ) {    
  449.                                         my $iTIKZ = index($_,"end{tikzpicture}");
  450.           if ($iTIKZ > 0) {
  451.             print PDF substr($_,$iTIKZ+16);            
  452.             $ignore = 0;
  453.             $type=-1;
  454.           }                                                                    
  455.         }                              
  456.       }
  457.     } else { print PDF $_; }
  458.  if (( index($_,"end{verbatim}") > 0 ) or ( index($_,"end{lstlisting}") > 0 )) { $iVerb = 0; }
  459.   }
  460.   close (FILE);
  461.   close (PDF);
  462.        
  463. if ($norun){print "Done\n";}
  464. else {
  465. system("pdflatex -interaction=batchmode $pdfname-pdf");
  466. if ($ppm){
  467. print "If you need to create JPG/PNG type cd $imageDir and run\n";
  468. print "mogrify -format jpg *.ppm\n";
  469. }
  470. print "Done\n";
  471. }
  472. if ( $clear ) {
  473.         unlink "$name.txt";
  474.         unlink "$tempDir/$name.aux";
  475.         unlink "$tempDir/$pdfname-pdf.log";
  476.         unlink "$tempDir/$pdfname-pdf.aux";
  477.         unlink "$tempDir/$pdfname-pdf-autopp.txt";
  478.         unlink "$tempDir/$pdfname-pics.pdf";
  479.         unlink "$tempDir/doc_data.txt";
  480.         unlink "$tempDir/$pdfname-tikz.tex";
  481.         unlink "$tempDir/$name-tikz.pdf";
  482.         unlink "$tempDir/$name-tikz.dvi";
  483.         unlink "$tempDir/$name-tikz.ps";
  484.         unlink "$tempDir/$name-tikz.aux";
  485.         unlink "$tempDir/$name-tikz.log";
  486.         unlink "$tempDir/$name.ps";
  487.         unlink "$tempDir/$name.dvi";
  488.         unlink "$tempDir/$name-pics.pdf";
  489.         unlink "$tempDir/$name-pics.tex";
  490.         unlink "$tempDir/$name-pics.aux";
  491.         unlink "$tempDir/$name-pics.log";
  492.  
  493.         }
  494. }
  495. sub LOG() {
  496.   if ( $verbose ) { print LOGfile "@_\n"; }
  497. }
  498. __END__
Coloreado en 0.013 segundos, usando GeSHi 1.0.8.4
lo que quiero decir, es que a veces lo utilizo para abrir/crear archivos y otras para abrir y crear directorios, ¿cómo cambio la línea 138 usando autodie?

PD: La linea 250 no corresponde a la original, perltidy la convirtio en
Sintáxis: [ Descargar ] [ Ocultar ]
  1. LOG ("all finished ... <img src="http://perlenespanol.com/foro/images/smilies/icon_smile.gif" alt=":-)" title="Smile" />"); 
pero deberia ser
Sintáxis: [ Descargar ] [ Ocultar ]
  1. LOG ("all finished ... :-)");  
pablgonz
Perlero nuevo
Perlero nuevo
 
Mensajes: 236
Registrado: 2010-09-08 21:03 @919
Ubicación: Concepción (Chile)

Re: Consulta sobre || y or

Notapor explorer » 2012-01-17 12:49 @575

Lo que hace autodie es un die() en todas las operaciones que tengan que ver con archivos y directorios (y algunas más. Consulta la página de manual para ver la lista completa).

Entonces, eso significa que podemos quitar todos los "or die ..." de nuestros programas.

La línea que indicas
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. open (LOGfile,">$Logfile") or die "cannot open $Logfile!";
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4
yo la escribiría como:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. open my $LOGFILE, '>', $Logfile;
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4
más en detalle:
  • Usamos una variable $LOGFILE, para guardar el controlador de archivo. Así es más fácil pasarlo a subrutinas. Y escrito en mayúsculas indica que, en cierta manera, es una constante a lo largo del programa
  • El open() está escrito de forma moderna: con tres argumentos, siendo el segundo la forma de apertura del archivo
  • No hay die(), porque ya puse 'use autodie;' al principio del programa

El perltidy no pone las caritas sonrientes. Es el software que renderiza estas páginas de foros. Cada vez que encuentra un texto que coincide con una cara sonriente, lo cambia por la imagen correspondiente.

Si no quieres que haga eso, a la hora de editar los mensajes, fíjate que hay una serie de opciones debajo de la caja de texto. Una de ellas se llama "Deshabilitar emoticonos".
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: Consulta sobre || y or

Notapor pablgonz » 2012-01-17 13:32 @605

Gracias por la explicación, eliminé todos los "or die" y cargué autodie, pero, ahora me arroja el siguiente error
Sintáxis: [ Descargar ] [ Ocultar ]
  1. Can't close filehandle 'FILE': 'Bad file descriptor' at tikz3pdf line 195 
si utilizo la opción force y
Sintáxis: [ Descargar ] [ Ocultar ]
  1. Can't close filehandle 'FILE': 'Bad file descriptor' at tikz3pdf line 212 
si utilizo -all, ¿por qué pasa esto ahora?, antes no me daba problemas y lo extraño es que si comento autodie funciona, ¿qué está mal escrito?
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. eval '(exit $?0)' && eval 'exec perl -S $0 ${1+"$@"}' && eval 'exec perl -S $0 $argv:q'
  2.   if 0;
  3.  
  4. use strict;                             # to be sure, that all is safe ... <img src="http://perlenespanol.com/foro/images/smilies/icon_smile.gif" alt=":-)" title="Smile" />
  5.  
  6. # $Id: tikz2pdf.pl 2012-01-17 08:41:35Z Pablo $
  7. # v. 0.1                                Extract tikzpicture, based on pst2pdf by Herbert Voss
  8. # 2012-01-17      (c) Pablo González Luengo
  9. # Thanks to Giuseppe Matarazzo
  10. # Couple to have the complete operation of the script, you need some software (Linux and Windows)
  11. # xpdf (needed to create EPS / PPM)
  12. # gnuplot (not necessary if not called from TiKZ)
  13. # pdftk (not necessary with the-pdftk)
  14. # ImageMagick (required if you want to create JPG / PNG or other format)
  15. #      
  16. use File::Path;  
  17. use File::Copy;  
  18. use File::Basename;    
  19. use IO::File;      
  20. use Getopt::Long;      
  21. use autodie;
  22. #----------------------- User part begin ------------------------
  23. my $imageDir = "images";       
  24. my $Iext = ".pdf";                      # leave empty, if not a special one
  25. my $tempDir = ".";                      # temporary directory
  26. my $verbose = 1;                          # 0 or 1, logfile  
  27. my $clear = 0;                            # 0 or 1, clears all temporary files
  28. my $DPI = 75;                               # very low value for the png's
  29. my $Iscale = 1;                           # for \includegraphics
  30. my $noImages = 0;                         # 1->create no images
  31. my $force = 0;                  # 1->force create images
  32. my $ppm = 0;                            # 1->create .ppm files
  33. my $norun = 0;                          # 1->runs pdflatex
  34. my $miktex = 0;                         # 1->runs pdlatex for miktex
  35. my $eps = 0;                            # 1->create .eps files
  36. my $ifiles = 0;                         # 1->create image files .tex
  37. my $all = 0;                            # 1->create all images and files for type
  38. my $nopdftk = 0;                                # 1->create all images and files for type in force mode
  39. #----------------------- User part end ---------------------------
  40. #----------------------- program identification, options and help
  41. my $program = "tikz2pdf";
  42. my $ident = '$Id: tikz2pdf.pl 2012-01-17 pablo $';
  43. my $copyright = <<END_COPYRIGHT ;
  44. Copyright 2012-01-17 (c) Pablo Gonzalez L <pablgonz\@yahoo.com>
  45. END_COPYRIGHT
  46. my $licensetxt= <<END_LICENSE ;
  47.     This program is free software; you can redistribute it and/or modify
  48.     it under the terms of the GNU General Public License as published by
  49.     the Free Software Foundation; either version 2 of the License, or
  50.     (at your option) any later version.
  51.  
  52.     This program is distributed in the hope that it will be useful, but
  53.     WITHOUT ANY WARRANTY; without even the implied warranty of
  54.     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  55.     General Public License for more details.
  56.  
  57.     You should have received a copy of the GNU General Public License
  58.     along with this program; if not, write to the Free Software
  59.     Foundation, Inc., 59 Temple Place, Suite 330, Boston,
  60.     MA  02111-1307  USA
  61. END_LICENSE
  62. my $title = "$program $ident\n";
  63. my $usage = <<"END_OF_USAGE";
  64. ${title}Usage: $program <texfile.tex>  [Options]
  65. tikz2pdf run a TeX source, and extract all TiKZ-related part as
  66.         single images  (pdf or eps or ppm, default pdf)
  67.         and then runs pdflatex. See tikz2pdf documentation for more info
  68. Options:
  69.   --help          - display this help and exit
  70.   --version       - display version information and exit
  71.   --license       - display license information and exit
  72.   --imageDir      - the dir for the created images (default images)
  73.   --DPI=<int>     - the dots per inch for a cretaed ppm files (default 75)
  74.   --ppm           - create .ppm files
  75.   --eps           - create .eps files  
  76.   --Iscale=<real> - the value for [scale=] in \\includegraphics
  77.   --noImages      - generate files without compile (need -norun)
  78.   --verbose       - creates long log
  79.   --clear         - delete all temp files
  80.   --norun         - create file-pdf.tex, but, no run pdflatex
  81.   --miktex        - for miktex users -enable-write18
  82.   --ifiles        - create images files (.tex) for all TiKZ enviroment 
  83.   --force         - create images whitout pdftk.
  84.   --all           - create all image type and images.tex       
  85.   --nopdftk          - create all image type and images.tex in force mode
  86. Examples:
  87. * $program test.tex --all
  88. * produce test-pdf.tex and ppm,eps,tex and pdf for TiKZ-enviroment in image dir
  89. END_OF_USAGE
  90. #
  91. my $result=GetOptions (
  92.                         "help",
  93.                         "version",
  94.                         "license",
  95.                         "DPI=i"      => \$DPI,          # numeric
  96.                         "Iscale=f"   => \$Iscale,       # real
  97.                         "imageDir=s" => \$imageDir,     # string
  98.                         "tempDir=s"  => \$tempDir,      # string
  99.                         "Iext=s"     => \$Iext,         # string
  100.                         "clear"      => \$clear,        # flag
  101.                         "noImages"   => \$noImages,     # flag
  102.                         "force"      => \$force,        # flag
  103.                         "ppm"        => \$ppm,         # flag
  104.                         "norun"      => \$norun,       # flag
  105.                         "miktex"     => \$miktex,      # flag
  106.                         "eps"        => \$eps,          # flag
  107.                         "ifiles"        => \$ifiles,            # flag
  108.                         "all"        => \$all,          # flag
  109.                         "nopdftk"        => \$nopdftk,          # flag
  110.                         "verbose"    => \$verbose,
  111. ) or die $usage;
  112. # help functions
  113. sub errorUsage { die "Error: @_ (try --help for more information)\n"; }
  114. # options for command line
  115. if ($::opt_help) {
  116.   print $usage;
  117.   exit (0);
  118. }
  119. if ($::opt_version) {
  120.   print $title;
  121.   print $copyright;
  122.   exit (0);
  123. }
  124. if ($::opt_license) {
  125.   print $licensetxt;
  126.   exit (0);
  127. }
  128. # open file
  129. my $InputFilename = "";
  130.   @ARGV > 0 or errorUsage "Input filename missing";
  131.   @ARGV < 2 or errorUsage "Unknown option or too many input files";
  132.   $InputFilename = $ARGV[0];
  133. # end open file
  134. my @SuffixList = (".tex","",".ltx");            # possible extensions
  135. my ($name,$path,$ext) = fileparse($ARGV[0],@SuffixList);
  136. if ($ext eq "") { $ext = ".tex"; }                      # me need the extension as well
  137. my $TeXfile = "$path$name$ext";
  138. my $Logfile = "$tempDir/$name.plog";            # our own log file
  139. open (LOGfile,">$Logfile") ;
  140. LOG ("Parameters:");
  141. LOG ("==> imageDir = $imageDir");
  142. LOG ("==> Iext     = $Iext");
  143. LOG ("==> DPI      = $DPI");
  144. LOG ("==> Iscale   = $Iscale");
  145. LOG ("==> tempDir  = $tempDir");
  146. LOG ("==> verbose  = $verbose");
  147. LOG ("==> clear    = $clear");
  148. LOG ("==> noImages = $noImages");
  149. LOG ("==> force    = $force");
  150. LOG ("==> ppm      = $ppm");
  151. LOG ("==> norun    = $norun");
  152. LOG ("==> miktex   = $miktex");
  153. LOG ("==> eps      = $eps");  
  154. LOG ("==> ifiles   = $ifiles");
  155. # General options
  156. if ($ppm) {
  157.   LOG ("Generate .ppm files ...");
  158.   $ppm = 1;
  159. }
  160. if ($norun) {
  161.   LOG ("no compile file-pdf.tex");
  162.   $norun = 1;
  163. }
  164. if ($miktex) {
  165.   LOG ("enable write 18 ...");
  166.   $miktex = 1;
  167. }
  168. if ($eps) {
  169.   LOG ("Generate .eps files ...");
  170.   $eps = 1;
  171. }
  172. if ($ifiles) {
  173.   LOG ("Generate .tex images files ...");
  174.   $ifiles=1;
  175. }
  176. if ($all) {
  177.   LOG ("Generate all images files ...");
  178.    $ifiles=$eps = $ppm = $clear = 1;
  179. }
  180. if ($nopdftk) {
  181.   LOG ("Forced generate all images files ...");
  182.   $force=$ifiles=$eps = $ppm = $clear = 1;
  183. }
  184. # Internal counter
  185. my $imgNo = 1;         
  186. # force mode , compile separte files
  187. if ($force) {
  188. LOG ("Running on [$path][$name][$ext]");
  189. open (FILE, "<$TeXfile") ;
  190. LOG ("force generate images...");
  191. if (-d $imageDir) { LOG ("$imageDir exists") }
  192. else { mkdir("$imageDir", 0744);}
  193. savePreamble($name);
  194. runFile($name);
  195. close FILE;                            
  196. close LOGfile;
  197. }
  198. else{
  199. LOG ("Running on [$path][$name][$ext]");
  200. open (FILE, "<$TeXfile") ;     
  201. if (!$noImages ) {
  202. if (-d $imageDir) { LOG ("$imageDir exists") }
  203. else {
  204. mkdir("$imageDir", 0744) ;
  205. LOG ("Imagedir created"); }
  206. LOG ("go to savePreamble ... ");
  207. runBurst($tempDir);
  208. savePreamble($name);
  209. runFile($name);
  210. LOG ("done!\n go to runFile ...");
  211. LOG ("done!");
  212. close FILE;                                    
  213. close LOGfile;
  214. }
  215. }
  216. #------------ Create filename-pics.pdf, split and generate .ppm
  217. sub runBurst{
  218. if ($force){ print "Force mode";}
  219. else{
  220. # Append preview
  221. my $entrada="$TeXfile";
  222. my $salida ="$name-pics.tex";
  223. open (ENTRADA,"<$entrada");
  224. open (SALIDA,">$salida") ;
  225.  print SALIDA "\\AtBeginDocument\{\n";
  226.  print SALIDA "\\RequirePackage\[active,tightpage\]\{preview\}\n";
  227.  print SALIDA "\\renewcommand\\PreviewBbAdjust\{-600pt -600pt 600pt 600pt\}\n";
  228.  print SALIDA "\\PreviewEnvironment\{tikzpicture\}\}\n";
  229.  while (my $linea=<ENTRADA>)
  230.   {
  231.         print SALIDA $linea;
  232.   }
  233. close (ENTRADA);
  234. close (SALIDA);
  235. # close preview
  236.  
  237. if ($miktex){system("pdflatex -enable-write18 -interaction=batchmode $name");}
  238. else{
  239. system("pdflatex -shell-escape -interaction=batchmode $tempDir/$name-pics.tex");
  240. system("pdfcrop $tempDir/$name-pics.pdf $tempDir/$name-pics.pdf");
  241. system("pdftk $name-pics.pdf burst output $imageDir/$name-tikz-\%1d.pdf");
  242. }
  243. if ($ppm){
  244. system("pdftoppm -r  $DPI $name-pics.pdf $imageDir/$name-tikz");
  245. }
  246. }
  247. }
  248. #------------ end pdftk burst
  249. LOG ("runpdfTeX ... ");
  250. runpdfTeX("$path$name",$name);
  251. LOG ("all finished ... <img src="http://perlenespanol.com/foro/images/smilies/icon_smile.gif" alt=":-)" title="Smile" />");
  252. if ( $clear ) {
  253. unlink "$path$name.txt";
  254. unlink "$path$name.log";
  255. unlink "$path$name.plog";
  256. unlink "$path$name.preamble";
  257. unlink "$path$name.pdf";
  258.  }
  259. # Save preable
  260. sub savePreamble {                             
  261.   my $filename = pop;
  262.   LOG ("----- Start Preamble -----");
  263.   open (FILEp, ">$tempDir/$filename.preamble") ;
  264.   while (<FILE>) {             
  265.     my $i = index($_,"begin{document}");
  266.     if ($i > 0) {
  267.       if ($i > 1) { print FILEp substr($_,0,--$i); }   
  268.                         if ($force) {
  269.                         print FILEp "\\pagestyle{empty}\n";
  270.                         }
  271.       close(FILEp);
  272.       LOG ("----- Close Preamble ------");
  273.       return;
  274.     } else {
  275.       print FILEp "$_";
  276.       LOG ("$_");
  277.     }
  278.   }
  279.   close(FILEp);
  280.   if ( $verbose ) { LOG("<-----Preamble<----"); }
  281.   return;
  282. }
  283.  
  284. sub searchTiKZ {                                       
  285.   my @TikZ = ();                                       
  286.   my @TIKZtotal = ();                  
  287.   my $depth = -1;                                      
  288.   my $type = -1;                                       
  289.   my $EndDocument = 0;         
  290.   my $iVerb = 0;                                       
  291.   while (<FILE>) {                             
  292.     if (!$EndDocument) {
  293.     chomp;                                                       
  294.     my $line = $_;                             
  295.     if ( !$iVerb ) {
  296.       $iVerb = ((index($line,"begin{verbatim}") > 0) or (index($line,"begin{lstlisting}") > 0));
  297.     }          
  298.     if ( !$iVerb ) {
  299.       my $iTIKZ = index($line,"begin{tikzpicture}");
  300.        if ( $type < 0 ) {                      
  301.       if ($iTIKZ > 0) {                        
  302.           $type = 2;                   
  303.           $line = substr($line,$iTIKZ-1);      
  304.           LOG("TiKZ-line: $line");
  305.         }                              
  306.        }
  307.  
  308. if ($type > 0) {
  309.         LOG ("searchTiKZ: set \$type=$type");
  310.         $iTIKZ = index($line,"end{tikzpicture}");      
  311.         if ($iTIKZ > 0) {              
  312.           LOG ("searchTiKZ: $line");
  313.                                 $type = -1;
  314.           push @TikZ,substr($line,0,$iTIKZ+16);
  315.           LOG ("searchTiKZ: set \$type=$type");
  316.           push @TIKZtotal,[@TikZ];                     
  317.           LOG ("---->TiKZ---->\n@TikZ\n<----TikZ<----");
  318.           @TikZ =();                   
  319.         } else { push @TikZ,$line; }    # add line
  320.       }
  321.       my $i = index($line,"end{document}");
  322.       if ($i > 0) { $EndDocument++; LOG("EndDocument in searchTiKZ"); }
  323.     }                  
  324.     if (( index($line,"end{verbatim}") > 0 ) or ( index($line,"end{lstlisting}") > 0 )) { $iVerb = 0; }
  325.   }}
  326.   if ( $verbose ) {
  327.     LOG("---->TIKZtotal---->");
  328.     for my $aref ( @TIKZtotal ) {
  329.       my @a = @$aref;
  330.       my $i = 1;
  331.                         foreach ( @a ) { LOG ($a[$i]); $i=$i+1; }
  332.     }
  333.     LOG ("<----TIKZtotal<----");
  334.   }
  335.   close(FILE);
  336.   return @TIKZtotal;   
  337. }
  338. # Creating ifile.tex and eps, pdf and ppm for images
  339. if ($force){
  340. sub runFORCE{
  341. my $filename = pop;
  342. if ($miktex){system("pdflatex -enable-write18 -interaction=batchmode $tempDir/$filename-tikz");}
  343. else{system("pdflatex -interaction=batchmode $tempDir/$filename-tikz");}
  344. if ($ifiles){
  345. copy("$filename-tikz.tex", "$imageDir/$filename-tikz-$imgNo.tex") ;
  346. }
  347. system("pdfcrop $tempDir/$filename-tikz.pdf $imageDir/$filename-tikz-$imgNo.pdf");  
  348. if ($eps) {system("pdftops -level3 -eps $imageDir/$filename-tikz-$imgNo.pdf $imageDir/$filename-tikz-$imgNo.eps");}
  349. if ($ppm) {system("pdftoppm -r $DPI $imageDir/$filename-tikz-$imgNo.pdf $imageDir/$filename-tikz-$imgNo");}
  350.     $imgNo=$imgNo+1;
  351.         }
  352. }
  353. else{
  354. # Creating ifiles.tex and .eps for images
  355. sub runTeX{
  356. my $filename = pop;
  357. if ($eps){
  358.                         system("pdftops -level3 -eps $imageDir/$filename-$imgNo.pdf $imageDir/$filename-$imgNo.eps");
  359.                    }
  360. if ($ifiles){
  361. copy("$filename.tex", "$imageDir/$filename-$imgNo.tex");
  362. }
  363. $imgNo=$imgNo+1;
  364. }
  365. }
  366. sub runFile {
  367.   my $filename = pop;
  368.   my @TIKZarray = searchTiKZ();
  369.   if ( $verbose ) {
  370.     LOG("---->TIKZarray---->");
  371.     for my $aref ( @TIKZarray ) {
  372.       my @a = @$aref;
  373.       my $i = 1;
  374.       foreach ( @a ) { print LOG $a[$i]."\n"; $i=$i+1; }
  375.     }
  376.     LOG("<----TIKZarray<----");
  377.     my $no = @TIKZarray;
  378.     LOG("TiKZ: ".$no." TiKZ sequence(s)");
  379.   }
  380.   for my $aref ( @TIKZarray ) {
  381.     my @TikZ = @$aref;
  382.     open (FILEp,"<$tempDir/$filename.preamble") ;
  383.     open (FILEsub,">$tempDir/$filename-tikz.tex") ;
  384.     while (<FILEp>) {print FILEsub $_; }
  385.                 print FILEsub "\\begin{document}\n";
  386.                 if ( $verbose ) { LOG("\@TikZ: $_"); }
  387.     foreach ( @TikZ ) { print FILEsub "$_\n"; }
  388.     print FILEsub "\\end{document}";
  389.     close (FILEsub);
  390.     close (FILEp);
  391.                 if ($force) {
  392.                 runFORCE("$name");
  393.                 }
  394.                 else{
  395.     runTeX("$tempDir/$name-tikz");
  396.   }
  397. }
  398. }
  399. # Renaming ppm need for correct name
  400. my $dren = "$tempDir/$imageDir";
  401. my $fichero = '';
  402. my $ppmren = '';
  403. my $renNo = 1;
  404. if(opendir(DIR,$dren)){
  405. foreach (readdir DIR){
  406.        $fichero = $_;
  407.                         if ( $fichero =~ /($name-tikz-)(\d+|\d+[-]\d+).ppm/) {
  408.         my $renNo   = int($2);
  409.         my $newname="$1$renNo.ppm";
  410.         $ppmren = rename("$dren/$fichero","$dren/$newname");
  411.         }
  412.         }
  413. }
  414. closedir DIR;
  415. # end renaming
  416. # Replace files
  417. sub runpdfTeX() {
  418.   my ($name,$pdfname) = @_;
  419.   open (PDF, ">$tempDir/$pdfname-pdf.tex") ;
  420.   open (FILE, "<$name.tex") ;
  421.         print PDF "\\RequirePackage{grfext}\n";
  422.         print PDF "\\PrependGraphicsExtensions*{$Iext}\n";
  423.         print PDF "\\RequirePackage{graphicx}\n";
  424.         print PDF "\\graphicspath{{$imageDir/}}\n";
  425.   my $ignore = 0;
  426.   my $IMGno = 1;
  427.   my $depth = -1;
  428.   my $type = -1;
  429.   my $EndDocument = 0;
  430.   my $iVerb = 0;
  431.   while (<FILE>) {
  432.     if ( !$iVerb ) {
  433.       $iVerb = ((index($_,"begin{verbatim}") > 0) or (index($_,"begin{lstlisting}") > 0));
  434.     }
  435.     if ( !$iVerb ) {
  436.       my $i = index($_,"end{document}");
  437.       if ($i > 0) { print PDF $_; $EndDocument++; LOG("EndDocument in runpdfTeX"); }
  438.       if ( !$EndDocument ) {
  439.         my $iTIKZ = index($_,"begin{tikzpicture}");
  440.         if ( $iTIKZ > 0 ) {
  441.           $type = 2;
  442.           $ignore = 1;
  443.           if ($iTIKZ > 1) { print PDF substr($_,0,--$iTIKZ); } 
  444.         print PDF "\\includegraphics[scale=$Iscale]{$pdfname-tikz-$IMGno}";
  445.           $IMGno=$IMGno+1;
  446.         }              
  447.         if ( !$ignore ) { print PDF "$_"; }    
  448.         if ( $type == 2 ) {    
  449.                                         my $iTIKZ = index($_,"end{tikzpicture}");
  450.           if ($iTIKZ > 0) {
  451.             print PDF substr($_,$iTIKZ+16);            
  452.             $ignore = 0;
  453.             $type=-1;
  454.           }                                                                    
  455.         }                              
  456.       }
  457.     } else { print PDF $_; }
  458.  if (( index($_,"end{verbatim}") > 0 ) or ( index($_,"end{lstlisting}") > 0 )) { $iVerb = 0; }
  459.   }
  460.   close (FILE);
  461.   close (PDF);
  462.        
  463. if ($norun){print "Done\n";}
  464. else {
  465. system("pdflatex -interaction=batchmode $pdfname-pdf");
  466. if ($ppm){
  467. print "If you need to create JPG/PNG type cd $imageDir and run\n";
  468. print "mogrify -format jpg *.ppm\n";
  469. }
  470. print "Done\n";
  471. }
  472. if ( $clear ) {
  473.         unlink "$name.txt";
  474.         unlink "$tempDir/$name.aux";
  475.         unlink "$tempDir/$pdfname-pdf.log";
  476.         unlink "$tempDir/$pdfname-pdf.aux";
  477.         unlink "$tempDir/$pdfname-pdf-autopp.txt";
  478.         unlink "$tempDir/$pdfname-pics.pdf";
  479.         unlink "$tempDir/doc_data.txt";
  480.         unlink "$tempDir/$pdfname-tikz.tex";
  481.         unlink "$tempDir/$name-tikz.pdf";
  482.         unlink "$tempDir/$name-tikz.dvi";
  483.         unlink "$tempDir/$name-tikz.ps";
  484.         unlink "$tempDir/$name-tikz.aux";
  485.         unlink "$tempDir/$name-tikz.log";
  486.         unlink "$tempDir/$name.ps";
  487.         unlink "$tempDir/$name.dvi";
  488.         unlink "$tempDir/$name-pics.pdf";
  489.         unlink "$tempDir/$name-pics.tex";
  490.         unlink "$tempDir/$name-pics.aux";
  491.         unlink "$tempDir/$name-pics.log";
  492.  
  493.         }
  494. }
  495. sub LOG() {
  496.   if ( $verbose ) { print LOGfile "@_\n"; }
  497. }
  498. __END__
Coloreado en 0.012 segundos, usando GeSHi 1.0.8.4
pablgonz
Perlero nuevo
Perlero nuevo
 
Mensajes: 236
Registrado: 2010-09-08 21:03 @919
Ubicación: Concepción (Chile)

Re: Consulta sobre || y or

Notapor explorer » 2012-01-17 14:25 @642

autodie mata el programa cuando ocurre un fallo en alguna de las funciones relacionadas con archivos. Y close() es una de ellas. Al llegar allí, se encuentra con que estás pretendiendo cerrar un archivo, que ya ha sido cerrado antes (posiblemente en la línea 335 y/o 460.

Es justo lo que te comentaba antes, del peligro de usar

open FILE,...

Si llamas ahora a una subrutina, y haces otro

open FILE,...

...

close FILE;

cuando vuelves de la subrutina, e intentas cerrar el fichero original,

close FILE;

salta el error, porque ya hiciste el close FILE dentro de la subrutina.

Por eso, siempre hay que usar

open my $FILE, ...

De esa manera, estamos creando una variable que es local al sitio -contexto, bloque cerrado de llaves- en donde esté el open(). Y no le afectará lo que pase en otras partes del programa.

Fíjate por dónde... autodie te ha ayudado a descubrir un error de tu programa que estaba muy escondido. Quizás no afectaba a la ejecución del programa, pero... si quizás cambias el programa en el futuro... sí que podría salir a la luz.
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: Consulta sobre || y or

Notapor pablgonz » 2012-01-17 14:48 @658

Muchas gracias por la pronta respuesta, explorer, haré los cambios necesarios y comento.

He buscado por la red alguna página o tutorial que diga «buenas practicas en perl», es decir, que comente detalles como estos, el uso de ||, or die() o la apertura de ficheros, si conoces alguno...

Supongo que deberé cambiar
Sintáxis: [ Descargar ] [ Ocultar ]
  1. open (FILE, "<$TeXfile") ; 
  2. ... 
  3. close FILE; 
a
Sintáxis: [ Descargar ] [ Ocultar ]
  1. open my $FILE, '<',"$TeXfile"; 
  2. ... 
  3. close my $FILE; 
pero, cuando uso while(), por ejemplo
Sintáxis: [ Descargar ] [ Ocultar ]
  1. while (<FILE>)  
¿también debo hacer el cambio a my $FILE?

Saludos
pablgonz
Perlero nuevo
Perlero nuevo
 
Mensajes: 236
Registrado: 2010-09-08 21:03 @919
Ubicación: Concepción (Chile)

Re: Consulta sobre || y or

Notapor explorer » 2012-01-17 15:27 @686

No, fíjate... el my() solo es necesario en el momento de crear la variable.

Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. open my $FILE, '>', $fichero;
  2. while (<$FILE>) {
  3.     say $FILE $salida;
  4. }
  5. close   $FILE;
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4


En cuanto a estilos de programación... lo recomendado es la lectura del libro Perl Best Practices (O'Reilly, Amazon) (guía rápida, presentación) o también usar los módulos de la rama Perl::Critic. Y en la documentación normal, puedes mirar, en tu propio ordenador, perldoc perlstyle (web) (traducido).

Lo mejor, para casos particulares, es consultar siempre la última documentación. En tu propio ordenador, ejecuta perldoc -f open (web). Aunque ahí solo hablan de open(), no dicen nada de autodie. Para ello, no queda más remedio que consultar la documentación de cada módulo.
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

Siguiente

Volver a Básico

¿Quién está conectado?

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

cron