• Publicidad

script Perl pst2pdf y pdfTeX

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

Re: script Perl pst2pdf y pdfTeX

Notapor pablgonz » 2011-06-04 09:11 @424

explorer escribiste:
pablgonz escribiste:2. Se podría, escribir el código cleanslp dentro del mismo pst2pdf y que ejecutara la misma acción, sin tener que reescribir todo pst2pdf.
Sí... no es más que un split(), una sustitución con una expresión regular, y luego un join().

Gracias por la pronta respuesta. Supongo que para lograr eso debería cambiar:
Sintáxis: [ Descargar ] [ Ocultar ]
  1. my $filemod = $ARGV[0]; 
a otra línea para abrir y modificar on the fly $tempDir/$pdfname-pdf.tex. Seguiré leyendo. Por el momento, el pst2pdf funciona, lo volveré a leer para ver cómo leer $tempDir/$pdfname-pdf.tex dentro del mismo script (que era mi intención original).

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

Publicidad

Re: script Perl pst2pdf y pdfTeX

Notapor explorer » 2011-06-04 12:26 @559

Esa línea sobra, desde luego... no vas a leer ningún argumento desde fuera.
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: script Perl pst2pdf y pdfTeX

Notapor pablgonz » 2011-06-04 15:41 @695

Mucho mejor si lo ingreso dentro del mismo pst2pdf (no sabía lo de las comillas). En fin, resulto así:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. ##-------Coment pstpackage in  preamble of pdfname-pdf.tex --------
  2. #-----Thanks to http://perlenespanol.com for the help given -----------
  3. my $tex_file = read_file("$pdfname-pdf.tex");                                # read
  4. my ($preamble, $body) = split /\\begin\{document\}/, $tex_file, 2;   # split
  5. $preamble =~ s/(\\usepackage){pst/\%\\usepackage{pst/g;              # mod
  6. write_file( "$pdfname-pdf.tex", $preamble, '\begin{document} ', $body);  # write
  7. ##----------------------- Close pdfname-pdf.tex --------------------------------
  8.  
Coloreado en 0.002 segundos, usando GeSHi 1.0.8.4


Muchas gracias a todos por la ayuda, daré el tema por cerrado, mis agradecimientos a pvaldes por su tiempo e ideas y a explorer por las aclaraciones en el código.

Y un última pregunta, ¿debo editar el post para reducir la cantidad de páginas o sólo se deja así?

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

Re: script Perl pst2pdf y pdfTeX

Notapor pablgonz » 2011-11-19 11:32 @522

Ahora, corre más rápido (mucho más rápido), puesto que no hago tantas llamadas a sistema y no proceso cada imagen por separado como en el original, y puedo correrlo tanto en Linux como en Windows. Mis más sinceros agradecimientos a los usuarios del foro, por sus respuestas, ideas y tutoriales, sin eso, no lo hubiese logrado jamás.

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

Re: script Perl pst2pdf y pdfTeX

Notapor pablgonz » 2011-12-15 23:12 @008

Vuelvo al foro con una nueva duda del script que me llevo a conocer el lenguaje, he añadido las opciones y funciona perfecto, pero he intentado añadir una nueva y no me funciona, ya he intentado varias opciones y revise los post del foro pero no encontré solución, tengo un problema con ! (negación), el script actual es este:
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: pst2pdf.pl 611 2011-12-14 08:41:35Z herbert $
  7. # v. 0.13                               simplify the use of PSTricks with pdf
  8. # 2011-12-12    (c) Herbert Voss <[email protected]>
  9. #                 Pablo González Luengo and http://perlenespanol.com
  10. #
  11. # This program is free software; you can redistribute it and/or modify
  12. # it under the terms of the GNU General Public License as published by
  13. # the Free Software Foundation; either version 2 of the License, or (at
  14. # your option) any later version.
  15. #
  16. # This program is distributed in the hope that it will be useful, but
  17. # WITHOUT ANY WARRANTY; without even the implied warranty of
  18. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  19. # See the GNU General Public License for more details.
  20. #
  21. # You should have received a copy of the GNU General Public License
  22. # along with this program; if not, write to the
  23. # Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
  24. # MA  02111-1307  USA
  25. #
  26. use File::Path;                         # creating/removing dirs
  27. use File::Copy;                         # copying files
  28. use File::Basename;                     # scan argument
  29. use IO::File;                           # simple IO operation
  30. use Getopt::Long;                       # read parameter
  31. #----------------------- User part begin ------------------------
  32. my $imageDir = "images";                # where to save the images
  33. my @imageType = ("eps","pdf");  # all image types
  34. my $Iext = ".pdf";                      # leave empty, if not a special one
  35. my $tempDir = ".";                      # temporary directory
  36. my $verbose = 1;                        # 0 or 1, logfile  
  37. my $clear = 0;                          # 0 or 1, clears all temporary files
  38. my $DPI = 75;                           # very low value for the png's
  39. my $Iscale = 1;                         # for \includegraphics
  40. my $noImages = 0;                       # 1->create no images
  41. my $force = 0;                  # 1->force create images
  42. my $runBibTeX = 0;                      # 1->runs bibtex
  43. my $runBiber = 0;                       # 1->runs biber and sets $runBibTeX=0
  44. my $ppm = 0;                            # 1->create .ppm files
  45. my $norun = 0;                          # 1->runs pdflatex
  46. my $miktex = 0;                         # 1->runs pdlatex for miktex
  47. my $eps = 0;                            # 1->create .eps files
  48. #----------------------- User part end ---------------------------
  49. #----------------------- program identification, options and help
  50. my $program = "pst2pdf";
  51. my $ident = '$Id: pst2pdf.pl 611 2011-12-14 08:41:35Z herbert $';
  52. my $copyright = <<END_COPYRIGHT ;
  53. Copyright 2011-01-18 (c) Herbert Voss <hvoss\@tug.org>
  54. END_COPYRIGHT
  55. my $licensetxt= <<END_LICENSE ;
  56.     This program is free software; you can redistribute it and/or modify
  57.     it under the terms of the GNU General Public License as published by
  58.     the Free Software Foundation; either version 2 of the License, or
  59.     (at your option) any later version.
  60.  
  61.     This program is distributed in the hope that it will be useful, but
  62.         WITHOUT ANY WARRANTY; without even the implied warranty of
  63.     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  64.         General Public License for more details.
  65.  
  66.     You should have received a copy of the GNU General Public License
  67.     along with this program; if not, write to the Free Software
  68.     Foundation, Inc., 59 Temple Place, Suite 330, Boston,
  69.         MA  02111-1307  USA
  70. END_LICENSE
  71. my $title = "$program $ident\n";
  72. my $usage = <<"END_OF_USAGE";
  73. ${title}Usage: $program <texfile.tex>  [Options]
  74. pst2pdf run a TeX source, and convert all PS-related part as
  75.         single images  (pdf or eps and/or png and/or ...)
  76.         and then runs pdflatex. See pst2pdf documentation for more info
  77. Options:
  78.   --help          - display this help and exit
  79.   --version       - display version information and exit
  80.   --license       - display license information and exit
  81.   --imageDir      - the dir for the created images (default images)
  82.   --DPI=<int>     - the dots per inch for a cretaed ppm files (default 75)
  83.   --ppm           - create .ppm files
  84.   --eps           - create .eps files  
  85.   --Iscale=<real> - the value for [scale=] in \\includegraphics
  86.         --noImages      - generate files without compile (need -norun)
  87.   --verbose       - creates long log
  88.   --clear         - delete all temp files
  89.   --norun         - create file-pdf.tex, but, no run pdflatex
  90.   --runBibTeX     - run bibtex on the aux file, if exists
  91.   --runBiber      - run biber on the bcf file, if exists
  92.   --miktex        - for miktex users -enable-write18   
  93.         --force         - create images whitout pdftk and auto-pst-pdf.
  94. Examples:
  95. * $program test.tex --clear --ppm --eps
  96. * produce test-pdf.tex and .ppm,.eps,.tex and .pdf for all images in image dir
  97. END_OF_USAGE
  98. #
  99. my $result=GetOptions (
  100.                         "help",
  101.                         "version",
  102.                         "license",
  103.                         "DPI=i"      => \$DPI,          # numeric
  104.                         "Iscale=f"   => \$Iscale,       # real
  105.                         "imageDir=s" => \$imageDir,     # string
  106.                         "tempDir=s"  => \$tempDir,      # string
  107.                         "Iext=s"     => \$Iext,         # string
  108.                         "clear"      => \$clear,        # flag
  109.                         "noImages"   => \$noImages,     # flag
  110.                         "force"          => \$force,    # flag
  111.                         "runBibTeX"  => \$runBibTeX,   # flag
  112.                         "ppm"        => \$ppm,         # flag
  113.                         "norun"      => \$norun,       # flag
  114.                         "miktex"     => \$miktex,      # flag
  115.                         "eps"        => \$eps,          # flag
  116.                         "runBiber"   => \$runBiber,     # flag
  117.                         "verbose"    => \$verbose,
  118. ) or die $usage;
  119. # help functions
  120. sub debug      { print STDERR "* @_\n" if $::opt_debug; }
  121. sub warning    { print STDERR "==> Warning: @_\n"; }
  122. sub error      { die "$title!!! Error: @_\n"; }
  123. sub errorUsage { die "Error: @_ (try --help for more information)\n"; }
  124. # options for command line
  125. if ($::opt_help) {
  126.   print $usage;
  127.   exit (0);
  128. }
  129. if ($::opt_version) {
  130.   print $title;
  131.   print $copyright;
  132.   exit (0);
  133. }
  134. if ($::opt_license) {
  135.   print $licensetxt;
  136.   exit (0);
  137. }
  138. # open file
  139. my $InputFilename = "";
  140. if ($::opt_filter) {
  141.   @ARGV == 0 or
  142.   errorUsage "Input file cannot be used with filter option";
  143.   debug "Filtering: will read standard input";
  144. } else {
  145.   @ARGV > 0 or errorUsage "Input filename missing";
  146.   @ARGV < 2 or errorUsage "Unknown option or too many input files";
  147.   $InputFilename = $ARGV[0];
  148.   debug "Input filename:", $InputFilename;
  149. }
  150. my @SuffixList = (".tex","",".ltx");            # possible extensions
  151. my ($name,$path,$ext) = fileparse($ARGV[0],@SuffixList);
  152. if ($ext eq "") { $ext = ".tex"; }                      # me need the extension as well
  153. my $TeXfile = "$path$name$ext";
  154. my $Logfile = "$tempDir/$name.plog";            # our own log file
  155. open (LOGfile,">$Logfile") or die "cannot open $Logfile!";
  156. LOG ("Parameters:");
  157. LOG ("==> imageDir = $imageDir");
  158. LOG ("==> Iext     = $Iext");
  159. LOG ("==> DPI      = $DPI");
  160. LOG ("==> Iscale   = $Iscale");
  161. LOG ("==> tempDir  = $tempDir");
  162. LOG ("==> verbose  = $verbose");
  163. LOG ("==> clear    = $clear");
  164. LOG ("==> noImages = $noImages");
  165. LOG ("==> force    = $force");
  166. LOG ("==> runBibTeX= $runBibTeX");
  167. LOG ("==> runBiber = $runBiber");
  168. LOG ("==> ppm      = $ppm");
  169. LOG ("==> norun    = $norun");
  170. LOG ("==> miktex   = $miktex");
  171. LOG ("==> eps      = $eps");  
  172.  
  173. if ($runBibTeX && $runBiber) {
  174.   LOG ("!!! you cannot run BibTeX and Biber at the same document ...");
  175.   LOG ("!!! Assuming to run Biber");
  176.   $runBibTeX = 0;
  177. }
  178. if ($ppm) {
  179.   LOG ("Generate .ppm files ...");
  180.   $ppm = 1;
  181. }
  182. if ($norun) {
  183.   LOG ("no compile file-pdf.tex");
  184.   $norun = 1;
  185. }
  186. if ($miktex) {
  187.   LOG ("enable write 18 ...");
  188.   $miktex = 1;
  189. }
  190. if ($eps) {
  191.   LOG ("Generate .eps files ...");
  192.   $eps = 1;
  193. }
  194.  
  195. my $imgNo = 1;                          # internal image counter
  196. my $pstExaLoaded = 0;           # Document loads pst-exa
  197.  
  198. #####proving force
  199. if ($force) {
  200. LOG ("Running on [$path][$name][$ext]");
  201. open (FILE, "<$TeXfile") or die "cannot open source file $TeXfile!";    # the source
  202. LOG ("force generate images...");
  203. runFORCE($name);
  204. savePreamble($name);
  205. close FILE;                                     # close source file
  206. close LOGfile;
  207. }
  208. else{
  209. LOG ("Running on [$path][$name][$ext]");
  210. open (FILE, "<$TeXfile") or die "cannot open source file $TeXfile!";    # the source
  211. if (!$noImages ) {
  212. if (-d $imageDir) { LOG ("$imageDir exists") }
  213. else { mkdir("$imageDir", 0744) || die "cannot mkdir $imageDir: $!";
  214. LOG ("Imagedir created"); }
  215. LOG ("go to savePreamble ... ");
  216. savePreamble($name);
  217. runFile("$name");
  218. runBurst("$tempDir");
  219. LOG ("done!\n go to runFile ...");
  220. LOG ("done!");
  221. close FILE;                                     # close source file
  222. close LOGfile;
  223. }# !noImages
  224. }
  225. #------------ Create filename-pics.pdf, split and generate .ppm
  226. sub runBurst{
  227. if ($force){ print "Force mode";}
  228. else{
  229. if ($miktex){system("pdflatex -enable-write18 -interaction=batchmode $tempDir/$name");}
  230. else{system("pdflatex -shell-escape -interaction=batchmode $tempDir/$name");}
  231. system("pdftk $name-pics.pdf burst output $imageDir/$name-tmp-\%1d.pdf");
  232. if ($ppm){system("pdftoppm -r  $DPI $name-pics.pdf $imageDir/$name-tmp"); }
  233. # Renaming .ppm neded for windows
  234. if ($^O eq 'MSWin32') {
  235. my $dren = "$tempDir/$imageDir";
  236. my $fichero = '';
  237. my $ppmren = '';
  238. my $renNo = 1;
  239. if(opendir(DIR,$dren)){
  240.   foreach (readdir DIR){
  241.         $fichero = $_;
  242.         if ($fichero =~ /([^\d]+)(\d+).ppm/){
  243.              my $renNo=int($2);
  244.              my $newname="$name-tmp-$renNo.ppm";
  245.           $ppmren = rename("$dren/$fichero","$dren/$newname");
  246.         }
  247.                 }
  248.         }
  249.   else
  250.         {
  251.   print "dont open".$dren;
  252.         }
  253. closedir DIR;
  254. }
  255. # end renaming
  256. }
  257. }
  258. #------------ end pdftk burst
  259. LOG ("runpdfTeX ... ");
  260. runpdfTeX("$path$name",$name);
  261. LOG ("all finished ... :-)");
  262.  
  263. if ( $clear ) {
  264. unlink "$path$name.txt";
  265. unlink "$path$name.log";
  266. unlink "$path$name.plog";
  267. unlink "$path$name.preamble";
  268. unlink "$path$name.pdf";
  269.  }
  270. # create a preamble file
  271. # if we have a \input command inside the preamble, it doesn't hurt, we need
  272. # it anyway for the postscript files and the pdf one.
  273. sub savePreamble {                             
  274.   my $filename = pop;                                   # get the file name
  275.   LOG ("----- Start Preamble -----");
  276.   open (FILEp, ">$tempDir/$filename.preamble")
  277.     or die "cannot open preamble file $tempDir/$filename.preamble!";
  278.   while (<FILE>) {                                      # read all until \begin{document}
  279.     $pstExaLoaded = index($_,"usepackage{pst-exa}");
  280.     my $i = index($_,"begin{document}");
  281.     if ($i > 0) {
  282.       if ($i > 1) { print FILEp substr($_,0,--$i); }    # write all until \begin{document}
  283.       close(FILEp);                                     # close preamble
  284.       LOG ("----- Close Preamble ------");
  285.       return;
  286.     } else {
  287.       print FILEp "$_";                                 # write into preamble
  288.       LOG ("$_");
  289.     }
  290.   }
  291.   close(FILEp);
  292.   if ( $verbose ) { LOG("<-----Preamble<----"); }
  293.   return;
  294. }
  295.  
  296. sub searchPS {                                          # search the PostScript parts
  297.   my @PS = ();                                          # single PS sequence
  298.   my @PStotal = ();                                     # all PS sequences as list of arrays
  299.   my $depth = -1;                                       # counts nested macros
  300.   my $type = -1;                                        # -1-> none; 1->PST; 2->PS;
  301.   my $EndDocument = 0;                                  # ignore all after \end{document}
  302.   my $iVerb = 0;                                        # test for verbatim or lstlisting environment, must be ignored
  303.   while (<FILE>) {                                      # scan the input file
  304.     if (!$EndDocument) {
  305.     chomp;                                                      # delete EOL character
  306.     my $line = $_;                                      # save line
  307.     if ( !$iVerb ) {
  308.       $iVerb = ((index($line,"begin{verbatim}") > 0) or (index($line,"begin{lstlisting}") > 0));
  309.     }                                                           # do nothing until \end{verbatim}
  310.     if ( !$iVerb ) {
  311.       my $iPS = index($line,"begin{postscript}");
  312.       my $iPST = index($line,"begin{pspicture*}");
  313.       if ($iPST < 0) { $iPST = index($line,"begin{pspicture}"); }       # alternative
  314.       if ($iPST < 0) { $iPST = index($line,"pspicture"); }                      # alternative \pspicture...
  315.       if (($iPS > 0) && ( $type == 1 )){ print "postscript environment must be of outer level!\n"; exit 1; }
  316.       if ( $type < 0 ) {                        # no active environment
  317.         if ($iPS > 0) {                         # we have \begin{postscript}
  318.           $type = 2;                   
  319.           $line = substr($line,$iPS-1);         # add rest of the line
  320.           LOG("PS-Zeile: $line");
  321.         }                              
  322.         elsif ( $iPST > 0 ) {                           # we have \begin{pspicture} or \pspicture
  323.           $type = 1;
  324.           $depth++;  
  325.           $line = substr($line,$iPST-1);        # add all unitl pspicture
  326.           LOG("PST-Zeile: $line");
  327.         }
  328.       }
  329. # we have now \begin{pspicture} or \begin{postscript}
  330.       if ($type > 0) {                                  # start Scan, we have an environment
  331.         LOG ("searchPS: set \$type=$type");
  332.         $iPST = index($line,"end{pspicture*}");
  333.         if ($iPST < 0) { $iPST = index($line,"end{pspicture}"); }       # alternative
  334.         if ($iPST < 0) { $iPST = index($line,"endpspicture"); }         # alternative \endpspicture...
  335.         $iPS = index($line,"end{postscript}"); 
  336.         if ($iPST > 0) {                                # test, we can have postscript and pspicture in one line
  337.           if ( $type < 2) {                             # found end of pspicture environment
  338.             LOG ("searchPS: $line");
  339.             $depth--;
  340.             if ($depth < 0) {
  341.               $type = -1;
  342.               if (index($line,"endpspicture") > 0)      # add line, depends to type
  343.                    { push @PS,substr($line,0,$iPST+12); }       # \endpspicture
  344.               elsif (index($line,"pspicture*") > 0)
  345.                       { push @PS,substr($line,0,$iPST+15); }# \end{pspicture}
  346.               else { push @PS,substr($line,0,$iPST+14); }       # \end{pspicture}
  347.               LOG ("searchPS: set \$type=$type");
  348.               push @PStotal,[@PS];      # add PS sequence
  349.               LOG ("---->PS---->\n@PS\n<----PS<----");
  350.               @PS = ();                 # start new PS sequence
  351.             }                           # no pspicture env left
  352.           } else { push @PS,$line; }    # pspicture inside postscript
  353.         } elsif ($iPS > 0) {            # must be type=1 -> stop Scan
  354.           LOG ("searchPS: $line");
  355.           $type = -1;
  356.           push @PS,substr($line,0,$iPS+15);     # add line
  357.           LOG ("searchPS: set \$type=$type");
  358.           push @PStotal,[@PS];                  # add PS sequence
  359.           LOG ("---->PS---->\n@PS\n<----PS<----");
  360.           @PS =();                      # start new PS sequence
  361.         } else { push @PS,$line; }      # add line
  362.       }
  363.       my $i = index($line,"end{document}");
  364.       if ($i > 0) { $EndDocument++; LOG("EndDocument in searchPS"); }
  365.     }                           # if ( $iVerb )
  366.     if (( index($line,"end{verbatim}") > 0 ) or ( index($line,"end{lstlisting}") > 0 )) { $iVerb = 0; }
  367.   }}
  368.   if ( $verbose ) {
  369.     LOG("---->PStotal---->");
  370.     for my $aref ( @PStotal ) {
  371.       my @a = @$aref;
  372.       my $i = 0;
  373.       foreach ( @a ) { LOG ($a[$i]); $i++; }
  374.     }
  375.     LOG ("<----PStotal<----");
  376.   }
  377.   close(FILE);
  378.   return @PStotal;              # return all PS sequences
  379. }
  380. # Creating subfiles.tex and .eps for images
  381. if ($force){
  382. sub runFORCE{
  383. my $filename = pop;
  384.   system("latex $filename"); # or die "Error in the LaTeX run from file $filename!";
  385.   system("dvips $filename"); # or die "Error in the dvips run from file $filename!";
  386.   system("ps2pdf $filename.ps");# or die "Error in the ps2pdf run from file $filename!";
  387.   copy("$filename.tex", "$imageDir/$filename-$imgNo.tex") or die "Cannot copy Source file!";;
  388.   for my $Itype ( @imageType ) {
  389.     if ($Itype eq "pdf") { system("pdfcrop $filename.pdf $imageDir/$filename-$imgNo.pdf");  }
  390.     if ($Itype eq "png") {
  391.       system("pdftoppm -f 1 -l 1 -r $DPI $imageDir/$filename-$imgNo.pdf $imageDir/");
  392.       system("convert $imageDir/-1.ppm  $imageDir/$filename-$imgNo.png");
  393.       system("rm $imageDir/-1.ppm");
  394.     }
  395.     if ($Itype eq "jpg") {
  396.       system("pdftoppm -f 1 -l 1 -r $DPI $imageDir/$filename-$imgNo.pdf $imageDir/");
  397.       system("convert $imageDir/-1.ppm  $imageDir/$filename-$imgNo.jpg");
  398.       system("rm $imageDir/-1.ppm");
  399.     }
  400.     if ($Itype eq "eps") { system("pdftops -f 1 -l 1 -eps $imageDir/$filename-$imgNo.pdf $imageDir/$filename-$imgNo.eps"); }
  401.   }
  402.   $imgNo=$imgNo+1;
  403. }
  404. }
  405. else{
  406. # Creating subfiles.tex and .eps for images
  407. sub runTeX{
  408.   my $filename = pop;
  409.   my $name = "$filename";
  410.   copy("$filename.tex", "$imageDir/$filename-$imgNo.tex") or die "Cannot copy Source file!";
  411.   if ($eps){
  412.                         system("pdftops -level3 -eps $imageDir/$filename-$imgNo.pdf $imageDir/$filename-$imgNo.eps");
  413.                    }
  414. $imgNo=$imgNo+1;
  415. }
  416. }
  417. sub runFile {
  418.   my $filename = pop;
  419.   my @PSarray = searchPS();
  420.   if ( $verbose ) {
  421.     LOG("---->PSarray---->");
  422.     for my $aref ( @PSarray ) {
  423.       my @a = @$aref;
  424.       my $i = 0;
  425.       foreach ( @a ) { print LOG $a[$i]."\n"; $i++; }
  426.     }
  427.     LOG("<----PSarray<----");
  428.     my $no = @PSarray;
  429.     LOG("PS: ".$no." PS sequence(s)");
  430.   }
  431.   for my $aref ( @PSarray ) {
  432.     my @PS = @$aref;
  433.     open (FILEp,"<$tempDir/$filename.preamble") or die "cannot open $tempDir/$filename.preamble!";
  434.     open (FILEsub,">$tempDir/$filename-tmp.tex") or die "cannot open $tempDir/$filename-tmp.tex!";
  435.     while (<FILEp>) {print FILEsub $_; }
  436.                 ### prueba modo fuerza
  437.                 if ($force) {
  438.                 print FILEsub "\\pagestyle{empty}\n";
  439.     print FILEsub "\\newenvironment{postscript}{}{}\n";
  440.     print FILEsub "\\begin{document}\n";
  441.                 }
  442.                 else{
  443.     print FILEsub "\\pagestyle{empty}\n";
  444.     print FILEsub "\\begin{document}\n";}
  445.     if ( $verbose ) { LOG("\@PS: $_"); }
  446.     foreach ( @PS ) { print FILEsub "$_\n"; }
  447.     print FILEsub "\\end{document}\n";
  448.     close (FILEsub);
  449.     close (FILEp);
  450.                 if ($force) {
  451.                 runFORCE("$tempDir/$filename-tmp");
  452.                 }
  453.                 else{
  454.     runTeX("$tempDir/$filename-tmp");
  455.   }
  456. }
  457. }
  458. # Replace files
  459. sub runpdfTeX() {
  460.   my ($name,$pdfname) = @_;
  461.   open (PDF, ">$tempDir/$pdfname-pdf.tex") or die "cannot open $tempDir/$pdfname-pdf.tex!";
  462.   open (FILE, "<$name.tex") or die "cannot open $name!";
  463.   my $ignore = 0;
  464.   my $IMGno = 1;
  465.   my $depth = -1;
  466.   my $type = -1;
  467.   my $EndDocument = 0;                                  # ignore all after \end{document}
  468.   my $iVerb = 0;
  469.   while (<FILE>) {                                      # scan the input file
  470.     if ( !$iVerb ) {
  471.       $iVerb = ((index($_,"begin{verbatim}") > 0) or (index($_,"begin{lstlisting}") > 0));
  472.     } # do nothing until \end{verbatim}|| \end{lstlisting}
  473.     if ( !$iVerb ) {
  474.       my $i = index($_,"end{document}");
  475.       if ($i > 0) { print PDF $_; $EndDocument++; LOG("EndDocument in runpdfTeX"); }
  476.       if ( !$EndDocument ) {
  477.         my $iPS = index($_,"begin{postscript}");
  478.         if ( $iPS > 0 ) {
  479.           $type = 2;
  480.           $ignore = 1;
  481.           if ($iPS > 1) { print PDF substr($_,0,--$iPS); }      # add preceeding text
  482.         print PDF "\\includegraphics[scale=$Iscale]{$pdfname-tmp-$IMGno}"; # use pdfname
  483.           $IMGno=$IMGno+1;
  484.         }               # postscript env
  485.         if ( $type < 2 ) {
  486.           my $iPST = index($_,"begin{pspicture*}");
  487.           if ($iPST < 0) { $iPST = index($_,"begin{pspicture}"); }      # alternative ...
  488.           if ($iPST < 0) { $iPST = index($_,"\\pspicture"); }           # alternative \endpspicture...
  489.           if ( $iPST >= 0 ) {                                   # start Scan
  490.             $ignore = 1;
  491.             $type = 1;
  492.             $depth++;                                                   # pspicture env
  493.             LOG("Increase depth: $depth");
  494.             if ( $depth == 0 ) {
  495.               if ($iPST > 1) { print PDF substr($_,0,--$iPST); }        # add preceeding text
  496.               print PDF "\\includegraphics[scale=$Iscale]{$pdfname-tmp-$IMGno}";        # use \graphicspath
  497.               $IMGno=$IMGno+1;
  498.               LOG("Increase Image counter: $IMGno");
  499.             }
  500.           }
  501.         }
  502.         if ( !$ignore ) { print PDF "$_"; }             # default line
  503.         if ( $type == 2 ) {                                             # postscript env
  504.           my $iPS = index($_,"end{postscript}");
  505.           if ($iPS > 0) {
  506.             print PDF substr($_,$iPS+15);               # rest of line
  507.             $ignore = 0;
  508.             $type=-1;
  509.           }                                                                             # end Scan
  510.         } elsif ( $type == 1 ) {                                # pspicture env
  511.           my $iPST = index($_,"end{pspicture*}");
  512.           if ($iPST < 0) { $iPST = index($_,"end{pspicture}"); }        # alternative ...
  513.           if ($iPST < 0) { $iPST = index($_,"endpspicture"); }          # alternative \endpspicture...
  514.           if ($iPST > 0) {                                              # end Scan
  515.             if (index($_,"endpspicture") > 0)           # add rest of line, depends to type
  516.                { print PDF substr($_,$iPST+12); }       # \endpspicture
  517.             elsif (index($_,"pspicture*") > 0)
  518.                     { print PDF substr($_,$iPST+15); }  # \end{pspicture*}
  519.             else    { print PDF substr($_,$iPST+14); }  # \end{pspicture}
  520.             $depth--;
  521.             LOG("Decrease depth: $depth");
  522.             if ($depth < 0) { $ignore = 0; }
  523.           }
  524.         }
  525.       } # if ( !$EndDocument )
  526.     } else { print PDF $_; } # if ( $iVerb )
  527.     if (( index($_,"end{verbatim}") > 0 ) or ( index($_,"end{lstlisting}") > 0 )) { $iVerb = 0; }
  528.   } # while (<FILE>)
  529.   close (FILE);
  530.   close (PDF);
  531. # Coment pst-package
  532.         open (IPDF, "<$tempDir/$pdfname-pdf.tex");
  533.         undef $/;   # read all file
  534.         my ($uno,$dos) = split(/\\begin\{document\}/,<IPDF>,2);
  535.         close IPDF;
  536.        
  537.         my @coment = split /\n/, $uno; # split in two
  538.         my @preamb;
  539.  
  540.         foreach my $line (@coment) {
  541.         chomp($line);
  542.         $line =~ s/\\usepackage(?:\[.+?\])?\{pst.+?}//g;                        # delete
  543.         $line =~ s/\\usepackage(?:\[.+?\])?\{psfr.+?}//g;                       # delete
  544.         $line =~ s/(\\usepackage(?:\[.+?\])?)\{auto-pst.+?}//g;         # delete
  545.         $line =~ s/(\\usepackage(?:\[.+?\])?)\{vaucanson-.+?}//g;       # delete
  546.         $line =~ s/(\\usepackage(?:\[.+?\])?)\{psgo}//g;        # delete
  547.         $line =~ s/(\\usepackage(?:\[.+?\])?)\{graph/\%$1\{graph/g; # comment
  548.         next if $line =~ m/^\s*$/;
  549.         push(@preamb,$line);    # adding changes
  550. }
  551. my $clean = join("\n", @preamb, "\\usepackage{grfext}\n\\\PrependGraphicsExtensions*{$Iext}\n\\usepackage{graphicx}\n\\graphicspath{{$imageDir/}}\n\\begin{document}\n". $dos);
  552.  
  553. open (OPDF,">$tempDir/$pdfname-pdf.tex"); # write changes
  554. print OPDF $clean;
  555. close OPDF;
  556. # close coment pst-package
  557.  
  558. my $runAgain = 0;
  559. if ($norun){print "Done\n";}
  560. else {system("pdflatex -interaction=batchmode $pdfname-pdf");}
  561. if (-e "$tempDir/$pdfname-pdf.idx") { system("makeindex $tempDir/$pdfname-pdf.idx"); $runAgain++; }
  562. if ($runBibTeX && -e "$tempDir/$pdfname-pdf.aux") { system("bibtex $tempDir/$pdfname-pdf");  $runAgain++; }
  563. if ($runBiber && -e "$tempDir/$pdfname-pdf.bcf") { system("biber $tempDir/$pdfname-pdf");  $runAgain++; }
  564. if ($runAgain) { system("pdflatex $tempDir/$pdfname-pdf"); }
  565. if ( $clear ) {
  566.         unlink "$name.txt";
  567.         unlink "$tempDir/$name.aux";
  568.         unlink "$tempDir/$pdfname-pdf.log";
  569.         unlink "$tempDir/$pdfname-pdf.aux";
  570.         unlink "$tempDir/$pdfname-pdf-autopp.txt";
  571.         unlink "$tempDir/$pdfname-pics.pdf";
  572.         unlink "$tempDir/doc_data.txt";
  573.         unlink "$tempDir/$pdfname-tmp.tex";
  574.         }
  575. }
  576.  
  577. sub LOG() {
  578.   if ( $verbose ) { print LOGfile "@_\n"; }
  579. }
  580. __END__
Coloreado en 0.017 segundos, usando GeSHi 1.0.8.4
y aquí viene mi pregunta, cuando quiero hacer que funcione la opción --force, me veo en la obligación de agregar ! en la línea 199
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. if (!$force) {
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4
con lo cual funciona la opcion --force, pero, dejan de funcionar el resto de las opciones que tengo, si quito ! funcionan todas las demás opciones a excepción de --force que me arroja un error, entonces, mi pregunta es, ¿está mal definido $force o me falta un if un else? o ¿debo definir todas las subrutinas de otra manera?
Esperando sus comentarios.
Pablo
pablgonz
Perlero nuevo
Perlero nuevo
 
Mensajes: 236
Registrado: 2010-09-08 21:03 @919
Ubicación: Concepción (Chile)

Re: script Perl pst2pdf y pdfTeX

Notapor explorer » 2011-12-16 08:39 @402

Hay más de un sitio donde preguntas por el valor de $force, como en la 381.

Creo que es un problema de lógica. Algunas opciones actúan de forma global, por lo que sí es necesario usar if-else, pero otras opciones solo tienen un ámbito local o afectan a un procedimiento muy pequeño, así que, realmente, no son casos nuevos de if-else, sino que deben ser tomados en cuenta en el mismo momento en que su ámbito entra en el proceso.

En el caso del if() de la línea 199, estás decidiendo por dos comportamientos muy distintos según la variable esté puesta o no. ¿Seguro que la parte de if(), cuando $force está puesta, contempla todos los casos del resto de opciones igual que cuando no está?
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: script Perl pst2pdf y pdfTeX

Notapor pablgonz » 2011-12-16 09:30 @437

explorer escribiste:Hay más de un sitio donde preguntas por el valor de $force, como en la 381.
Creo que es un problema de lógica. Algunas opciones actúan de forma global, por lo que sí es necesario usar if-else, pero otras opciones solo tienen un ámbito local o afectan a un procedimiento muy pequeño, así que, realmente, no son casos nuevos de if-else, sino que deben ser tomados en cuenta en el mismo momento en que su ámbito entra en el proceso.

Tienes toda la razón, es un problema de lógica, no tenía creado el directorio images que es donde se compiló. Cambié el código a esto
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. if ($force) {
  2. LOG ("Running on [$path][$name][$ext]");
  3. open (FILE, "<$TeXfile") or die "cannot open source file $TeXfile!";    # the source
  4. LOG ("force generate images...");
  5. if (-d $imageDir) { LOG ("$imageDir exists") }
  6. else { mkdir("$imageDir", 0744) || die "cannot mkdir $imageDir: $!";}
  7. savePreamble($name);
  8. runFile($name);
  9. runFORCE("$tempDir/$name");
  10. close FILE;                                     # close source file
  11. close LOGfile;
  12. }
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4
con lo cual resolví el problema de !, pero ahora tengo un problema parcial: si no utilizo la opción --force, me arroja un I/O error: trata de buscar name-tmp-numero.pdf al inicio, es decir, debo correr el script dos veces para que trabaje en forma correcta, lo cual no debería pasar. La línea 230 crea el archivo y la 231 los separa...

Seguiré probando.
Gracias por tu respuesta.
Pablo
pablgonz
Perlero nuevo
Perlero nuevo
 
Mensajes: 236
Registrado: 2010-09-08 21:03 @919
Ubicación: Concepción (Chile)

Re: script Perl pst2pdf y pdfTeX

Notapor explorer » 2011-12-16 10:16 @470

Poniendo print() del estilo

print "Ahora estoy <haciendo-algo>\n";

a lo largo del código, sabrás qué está haciendo y por dónde se está ejecutando el programa.
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: script Perl pst2pdf y pdfTeX

Notapor pablgonz » 2011-12-16 12:37 @567

Encontré el problema... tenía un subRUN(); corriendo en el directorio equivocado(las benditas comillas para variar), por eso me daba el error... Me queda una última pregunta, ¿cómo puedo definir una opción que reúna otras?

Me explico: deseo que
Sintáxis: [ Descargar ] [ Ocultar ]
  1. -eps -ppm -clear 
se puedan llamar de una sola vez algo así como un alias, por ejemplo
Sintáxis: [ Descargar ] [ Ocultar ]
  1. -all= -eps -ppm -clear 

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

Re: script Perl pst2pdf y pdfTeX

Notapor explorer » 2011-12-16 15:02 @668

Solo tienes que agregar -all como una opción más. Y luego, en la línea 138, solo tienes que hacer un if(), para preguntar si está puesta, y si es el caso, pones los valores correspondientes a las variables de las opciones que sustituye -all.

Algo así:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. if ($all) {
  2.     $eps = $ppm = $clear = 1;
  3. }
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4
JF^D Perl programming & Raku programming. Grupo en Telegram: https://t.me/Perl_ES
Avatar de Usuario
explorer
Administrador
Administrador
 
Mensajes: 14480
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España

AnteriorSiguiente

Volver a Básico

¿Quién está conectado?

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

cron