Perl en Español

  1. Home
  2. Tutoriales
  3. Foro
  4. Artículos
  5. Donativos
  6. Publicidad
 
Índice general » Mundo Perl » Básico » Consulta sobre || y or  RESUELTO Responder al tema
Nuevo tema


Página 1 de 2  [ 16 mensajes ]  Ir a página 1, 2  Siguiente
 
Nota 2012-01-17 11:23 @516

Perlero Nuevo
Registrado: 2010-09-08 21:03 @919
Mensajes: 61
Consulta sobre || y or
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


Nota 2012-01-17 11:43 @529
Avatar de Usuario
Administrador
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España
Mensajes: 10249
Re: Consulta sobre || y or
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:

Syntax: [ Download ] [ Hide ]
Using perl Syntax Highlighting
if ($linea == 23  or  $linea == 24) {

_________________
JF^D Perl programming


Nota 2012-01-17 11:58 @540

Perlero Nuevo
Registrado: 2010-09-08 21:03 @919
Mensajes: 61
Re: Consulta sobre || y or
Gracias por la aclaración, supongo que en situaciones como esta también es valido (y preferible) cambiar
Syntax: [ Download ] [ Hide ]
Using perl Syntax Highlighting
  1. mkdir("$imageDir", 0744) || die "cannot mkdir $imageDir: $!";
por
Syntax: [ Download ] [ Hide ]
Using perl Syntax Highlighting
  1. mkdir("$imageDir", 0744) or die "cannot mkdir $imageDir: $!";


Nota 2012-01-17 12:06 @546
Avatar de Usuario
Administrador
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España
Mensajes: 10249
Re: Consulta sobre || y or
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:

Syntax: [ Download ] [ Hide ]
Using perl Syntax Highlighting
  1. use autodie;               # "Es mejor morir que regresar con deshonor --Proverbio Kinglon"
  2.  
  3. mkdir $imageDir, 0744;

Queda mucho más corto, ¿verdad? :)
Ejemplo:
Syntax: [ Download ] [ Hide ]
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.  

_________________
JF^D Perl programming


Nota 2012-01-17 12:22 @557

Perlero Nuevo
Registrado: 2010-09-08 21:03 @919
Mensajes: 61
Re: Consulta sobre || y or
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:
Syntax: [ Download ] [ Hide ]
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__
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
Syntax: [ Download ] [ Hide ]
  1. LOG ("all finished ... <img src="http://perlenespanol.com/foro/images/smilies/icon_smile.gif" alt=":-)" title="Smile" />"); 
pero deberia ser
Syntax: [ Download ] [ Hide ]
  1. LOG ("all finished ... :-)");  


Nota 2012-01-17 12:49 @575
Avatar de Usuario
Administrador
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España
Mensajes: 10249
Re: Consulta sobre || y or
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
Syntax: [ Download ] [ Hide ]
Using perl Syntax Highlighting
  1. open (LOGfile,">$Logfile") or die "cannot open $Logfile!";
yo la escribiría como:
Syntax: [ Download ] [ Hide ]
Using perl Syntax Highlighting
  1. open my $LOGFILE, '>', $Logfile;
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


Nota 2012-01-17 13:32 @605

Perlero Nuevo
Registrado: 2010-09-08 21:03 @919
Mensajes: 61
Re: Consulta sobre || y or
Gracias por la explicación, eliminé todos los "or die" y cargué autodie, pero, ahora me arroja el siguiente error
Syntax: [ Download ] [ Hide ]
  1. Can't close filehandle 'FILE': 'Bad file descriptor' at tikz3pdf line 195 
si utilizo la opción force y
Syntax: [ Download ] [ Hide ]
  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?
Syntax: [ Download ] [ Hide ]
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__


Nota 2012-01-17 14:25 @642
Avatar de Usuario
Administrador
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España
Mensajes: 10249
Re: Consulta sobre || y or
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


Nota 2012-01-17 14:48 @658

Perlero Nuevo
Registrado: 2010-09-08 21:03 @919
Mensajes: 61
Re: Consulta sobre || y or
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
Syntax: [ Download ] [ Hide ]
  1. open (FILE, "<$TeXfile") ; 
  2. ... 
  3. close FILE; 
a
Syntax: [ Download ] [ Hide ]
  1. open my $FILE, '<',"$TeXfile"; 
  2. ... 
  3. close my $FILE; 
pero, cuando uso while(), por ejemplo
Syntax: [ Download ] [ Hide ]
  1. while (<FILE>)  
¿también debo hacer el cambio a my $FILE?

Saludos


Nota 2012-01-17 15:27 @686
Avatar de Usuario
Administrador
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España
Mensajes: 10249
Re: Consulta sobre || y or
No, fíjate... el my() solo es necesario en el momento de crear la variable.

Syntax: [ Download ] [ Hide ]
Using perl Syntax Highlighting
  1. open my $FILE, '>', $fichero;
  2. while (<$FILE>) {
  3.     say $FILE $salida;
  4. }
  5. close   $FILE;


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


Nota 2012-01-17 16:31 @730

Perlero Nuevo
Registrado: 2010-09-08 21:03 @919
Mensajes: 61
Re: Consulta sobre || y or
explorer escribió:
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.
Justo lo que pensaste: cambié las formas de abrir los archivos, pero no puedo dar con la línea que abre FILE, el cual estoy cerrando en la 335... misma situación con la 460.

Con autodie me di cuenta que tenía un par de cosas demás (unos unlink() de sobra), pero ahora no puedo avanzar por el error de la línea 335.

En fin, seguiré depurando a ver qué puedo lograr.

Gracias por la información de los textos, veré si tienen alguno en la biblioteca de la universidad.
Saludos


Nota 2012-01-17 18:40 @819
Avatar de Usuario
Administrador
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España
Mensajes: 10249
Re: Consulta sobre || y or
Esto es lo que pasa:
  • haces los open() en las líneas 188 y 199
  • después, ejecutas RunFile(), en las líneas 193 y 208
  • RunFile, en la línea 366, lo primero que hace es llamar a searchTiKZ, en la 368
  • searchTiKZ, en la línea 284, hace un bucle while(<FILE>) en la 291, y el close de la 335
  • regresa el control a las líneas anteriores, y aparecen nuevos close en las líneas 195 y 221, y ahí sale el fallo, pues ya estaban cerrados en la 335.
En cuanto a la otra parte, la del open() de la 419, está bien, porque haces también el while() (línea 431) y el close() (línea 460), en la misma subrutina.

_________________
JF^D Perl programming


Nota 2012-01-17 23:21 @015

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


Última edición por pablgonz el 2012-01-18 15:34 @690, editado 2 veces en total

Nota 2012-01-18 06:57 @331
Avatar de Usuario
Administrador
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España
Mensajes: 10249
Re: Consulta sobre || y or
Formateando el código con Perltidy, queda claro que el close() de la línea 223 debería estar después de la 225.

_________________
JF^D Perl programming


Nota 2012-01-18 15:37 @692

Perlero Nuevo
Registrado: 2010-09-08 21:03 @919
Mensajes: 61
Re: Consulta sobre || y or
Cambie la linea que me indicaste y edite el código que estaba más arriba (ahora usando Perltidy :D ), agregue los unlink que necesitaba y modifique un par de cosas que me faltaban, ¿alguna sugerencia respecto al código? (errores, etc.)


Responder al tema  [ 16 mensajes ]  Ir a página 1, 2  Siguiente

Reglas del Foro
No puedes abrir nuevos temas en este Foro
No puedes responder a temas en este Foro
No puedes editar tus mensajes en este Foro
No puedes borrar tus mensajes en este Foro
No puedes enviar adjuntos en este Foro

Publicidad

Socializa

Síguenos por Twitter

Suscríbete GRATUITAMENTE al Boletín de Perl en Español

Saltar a:  
Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
Traducción al español por Huan Manwë para phpbb-es.com
phpBB SEO