• Publicidad

Duda con elsif, quiebro de línea y array en script

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

Duda con elsif, quiebro de línea y array en script

Notapor pablgonz » 2012-03-28 21:11 @924

Amigos del foro, dispongo del siguiente script con el cual me han ayudado en ocasiones anteriores (modificado y funcionando al 100%). Añadí algunas líneas y me han asaltado algunas dudas, código:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. eval '(exit $?0)' && eval 'exec perl -S $0 ${1+"$@"}' && eval 'exec perl -S $0 $argv:q'
  2.     if 0;
  3.  
  4. use strict;                            # to be sure, that all is safe ... :-)
  5.  
  6. # $Id: tikzimg.pl 2012-02-10 Pablo $
  7. # v. 1.0   Extract tikzpicture, based on pst2pdf by Herbert Voss
  8. # 2012-02-10      (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, called poppler-utils in Linux)
  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/SVG 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 ppm files
  29. my $Iscale   = 1;                      # for \includegraphics
  30. my $noImages = 0;                      # 1->create no images
  31. my $single   = 0;                      # 1->create images in single mode
  32. my $ppm      = 0;                      # 1->create .ppm files
  33. my $norun    = 0;                      # 1->create file, but not compiled
  34. my $miktex   = 0;                      # 1->run in miktex distro
  35. my $eps      = 0;                      # 1->create .eps files
  36. my $files    = 0;                      # 1->create file.tex for all enviroment
  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. my $xetex    = 0;                      # 1->create all images using xelatex
  40. my $luatex   = 0;                      # 1->create all images using lualatex
  41.  
  42. #----------------------- User part end ---------------------------
  43. #-----------------program identification, options and help--------
  44. my $program   = "tikzimg";
  45. my $ident     = '$Id: tikzimg v1.0, 2012-02-10 pablo $';
  46. my $copyright = <<END_COPYRIGHT ;
  47. Copyright 2012-02-10 (c) Pablo Gonzalez L <pablgonz\@yahoo.com>
  48. END_COPYRIGHT
  49. my $licensetxt = <<END_LICENSE ;
  50.     This program is free software; you can redistribute it and/or modify
  51.     it under the terms of the GNU General Public License as published by
  52.     the Free Software Foundation; either version 2 of the License, or
  53.     (at your option) any later version.
  54.  
  55.     This program is distributed in the hope that it will be useful, but
  56.     WITHOUT ANY WARRANTY; without even the implied warranty of
  57.     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  58.     General Public License for more details.
  59.  
  60.     You should have received a copy of the GNU General Public License
  61.     along with this program; if not, write to the Free Software
  62.     Foundation, Inc., 59 Temple Place, Suite 330, Boston,
  63.     MA  02111-1307  USA
  64. END_LICENSE
  65. my $title = "$program $ident\n";
  66. my $usage = <<"END_OF_USAGE";
  67. ${title}Usage: $program <texfile.tex>  [options]
  68. tikzimg run a LaTeX file, and extract all TiKZ-related part as
  69.         single images  (pdf or eps or ppm, default pdf) and
  70.                                 then runs (pdf/Xe/Lua)latex. See tikzimg
  71.                                 documentation for more info.
  72. Options:
  73.   --h|help          - display this help and exit
  74.   --v|version       - display version information and exit
  75.   --l|license       - display license information and exit
  76.   --imageDir      - the dir for the created images (default images)
  77.   --DPI=<int>       - the dots per inch for a cretaed ppm files (default 75)
  78.   --p|ppm           - create .ppm files
  79.   --e|eps           - create .eps files  
  80.   --Iscale=<real>         - the value for [scale=] in \\includegraphics
  81.   --noImages      - generate files without compile (need -norun)
  82.   --Verbose         - creates long log
  83.   --c|clear         - delete all temp files
  84.   --n|norun         - create file-pdf.tex, but, no run pdflatex
  85.   --m|miktex        - for miktex users -enable-write18
  86.   --f|files         - create images files (.tex) for all TiKZ enviroment
  87.   --s|single        - create images whitout pdftk.
  88.   --all             - create all image type and images.tex      
  89.   --nopdftk         - create all image type and images.tex in single mode
  90.   --xetex           - create all image using xelatex
  91.   --luatex          - create all image using lualatex
  92. Examples:
  93. * $program test.tex --all
  94. * produce test-pdf.tex and .ppm,.eps,.tex,.pdf
  95. * for all TiKZ-enviroment.
  96. END_OF_USAGE
  97. #
  98. my $result = GetOptions(
  99.     'h|help'    => \$::opt_help,
  100.     'v|version'         => \$::opt_version,
  101.     'l|license'         => \$::opt_license,
  102.     'd|DPI=i'           => \$DPI,
  103.     "Iscale=f"          => \$Iscale,
  104.     'id|imageDir=s' => \$imageDir,
  105.     "tempDir=s"   => \$tempDir,
  106.     "Iext=s"      => \$Iext,
  107.     'c|clear'     => \$clear,
  108.     "noImages"  => \$noImages,
  109.     's|single'    => \$single,
  110.     'p|ppm'       => \$ppm,
  111.     'n|norun'     => \$norun,
  112.     'm|miktex'    => \$miktex,
  113.     'e|eps'       => \$eps,
  114.     'f|files'     => \$files,
  115.     'a|all'       => \$all,
  116.     "nopdftk"     => \$nopdftk,
  117.     "Verbose"     => \$Verbose,
  118.     "xetex"       => \$xetex,
  119.     "luatex"      => \$luatex,
  120. ) or die $usage;
  121.  
  122. # help functions
  123. sub errorUsage { die "Error: @_ (try --help for more information)\n"; }
  124.  
  125. # options for command line
  126. if ($::opt_help) {
  127.     print $usage;
  128.     exit(0);
  129. }
  130. if ($::opt_version) {
  131.     print $title;
  132.     print $copyright;
  133.     exit(0);
  134. }
  135. if ($::opt_license) {
  136.     print $licensetxt;
  137.     exit(0);
  138. }
  139.  
  140. # open file
  141. my $InputFilename = "";
  142. @ARGV > 0 or errorUsage "Input filename missing";
  143. @ARGV < 2 or errorUsage "Unknown option or too many input files";
  144. $InputFilename = $ARGV[0];
  145.  
  146. # end open file
  147. my @SuffixList = ( ".tex", "", ".ltx" );    # possible extensions
  148. my ( $name, $path, $ext ) = fileparse( $ARGV[0], @SuffixList );
  149. if ( $ext eq "" ) { $ext = ".tex"; }   # me need the extension as well
  150. my $TeXfile = "$path$name$ext";
  151. open  my $LOGfile,'>', "$tempDir/$name.plog";
  152. LOG("Parameters:");
  153. LOG("==> imageDir = $imageDir");
  154. LOG("==> Iext     = $Iext");
  155. LOG("==> DPI      = $DPI");
  156. LOG("==> Iscale   = $Iscale");
  157. LOG("==> tempDir  = $tempDir");
  158. LOG("==> Verbose  = $Verbose");
  159. LOG("==> clear    = $clear");
  160. LOG("==> noImages = $noImages");
  161. LOG("==> single   = $single");
  162. LOG("==> ppm      = $ppm");
  163. LOG("==> miktex   = $miktex");
  164. LOG("==> eps      = $eps");
  165. LOG("==> files    = $files");
  166. LOG("==> xetex    = $xetex");
  167. LOG("==> luatex   = $luatex");
  168.  
  169. # General options
  170. if ($ppm) {
  171.     LOG("Generate .ppm files ...");
  172.     $ppm = 1;
  173. }
  174. if ($norun) {
  175.     LOG("no compile file-pdf.tex");
  176.     $norun = 1;
  177. }
  178. if ($miktex) {
  179.     LOG("enable write 18 ...");
  180.     $miktex = 1;
  181. }
  182. if ($eps) {
  183.     LOG("Generate .eps files ...");
  184.     $eps = 1;
  185. }
  186. if ($files) {
  187.     LOG("Generate .tex images files ...");
  188.     $files = 1;
  189. }
  190. if ($all) {
  191.     LOG("Generate all images files ...");
  192.     $files = $eps = $ppm = $clear = 1;
  193. }
  194. if ($nopdftk) {
  195.     LOG("Generate all images in single mode ...");
  196.     $single = $files = $eps = $ppm = $clear = 1;
  197. }
  198. if ($xetex) {
  199.     LOG("Generate all images using XeLaTeX");
  200.     $xetex = 1;
  201. }
  202. if ($luatex) {
  203.     LOG("Generate all images using LuaLaTeX");
  204.     $luatex = 1;
  205. }
  206. # Internal image counter
  207. my $imgNo = 1;
  208.  
  209. # ------------------ simgle mode , compile separte files
  210. if ($single) {
  211.     LOG("Running on [$path][$name][$ext]");
  212.     open my $FILE, '<', "$TeXfile";
  213.     LOG("Generate images in single mode...");
  214.     if   ( -d $imageDir ) { LOG("$imageDir exists") }
  215.     else { mkdir $imageDir, 0744; }
  216.     savePreamble($name);
  217.     runFile($name);
  218.     close $FILE;
  219.     close $LOGfile;
  220. }
  221. else {
  222.     LOG("Running on [$path][$name][$ext]");
  223.     open my $FILE, '<', "$TeXfile";
  224.     if ( !$noImages) {if ( -d $imageDir ) { LOG("$imageDir exists") }
  225.     else {mkdir $imageDir, 0744;
  226.         LOG("Imagedir created");
  227.         }
  228.         LOG("go to savePreamble ... ");
  229.         runBurst($tempDir);
  230.         savePreamble($name);
  231.         runFile($name);
  232.         LOG("done!\n go to runFile ...");
  233.         LOG("done!");
  234.         close $LOGfile;
  235.     }
  236.           close $FILE;
  237. }
  238.  
  239. #------------ Create filename-pics.pdf, split and generate .ppm
  240. sub runBurst {
  241.     if ($single) { print "Force mode"; }
  242.     else {
  243.         my $entrada = "$TeXfile";
  244.         my $salida  = "$name-pics.tex";
  245.         open my $ENTRADA,'<', "$entrada";
  246.         open my $SALIDA,'>',"$salida";
  247.         print $SALIDA "\\AtBeginDocument\{\n";
  248.         if($xetex){
  249.         print $SALIDA "\\RequirePackage\[xetex,active,tightpage\]\{preview\}\n";}
  250.         else{
  251.           print $SALIDA "\\RequirePackage\[active,tightpage\]\{preview\}\n";}
  252.         print $SALIDA "\\renewcommand\\PreviewBbAdjust\{-600pt -600pt 600pt 600pt\}\n";
  253.           print $SALIDA "\\newenvironment{tikzexport}{}{}\n";
  254.           print $SALIDA "\\PreviewEnvironment\{tikzexport\}\n";
  255.         print $SALIDA "\\PreviewEnvironment\{tikzpicture\}\}\n";
  256.  
  257.         while ( my $linea = <$ENTRADA> ) {
  258.         print $SALIDA $linea;
  259.         }
  260.         close $ENTRADA;
  261.         close $SALIDA;
  262.     if($xetex){
  263.       if ($miktex){
  264.           system("xelatex -enable-write18 -interaction=batchmode $tempDir/$name-pics.tex");}
  265.       else{
  266.           system("xelatex -shell-escape -interaction=batchmode $tempDir/$name-pics.tex");}
  267.           system("pdfcrop -xetex -margin 2 $tempDir/$name-pics.pdf $tempDir/$name-pics.pdf");
  268.            }
  269.         elsif($luatex){
  270.      if ($miktex){
  271.         system("lualatex -enable-write18 -interaction=batchmode $tempDir/$name-pics.tex");}
  272.         else{
  273.         system("lualatex -shell-escape -interaction=batchmode $tempDir/$name-pics.tex");}
  274.         system("pdfcrop -luatex -margin 2 $tempDir/$name-pics.pdf $tempDir/$name-pics.pdf");
  275.                 }
  276.         else{
  277.        if ($miktex){
  278.         system("pdflatex -enable-write18 -interaction=batchmode $tempDir/$name-pics.tex");}
  279.         else{
  280.         system("pdflatex -shell-escape -interaction=batchmode $tempDir/$name-pics.tex");}
  281.         system("pdfcrop -margin 2 $tempDir/$name-pics.pdf $tempDir/$name-pics.pdf");
  282.         }
  283.         system("pdftk $name-pics.pdf burst output $imageDir/$name-tikz-\%1d.pdf");
  284.        
  285.     if($ppm){
  286.             system("pdftoppm -r  $DPI $name-pics.pdf $imageDir/$name-tikz");
  287.         }
  288.     }
  289. }
  290.  
  291. #------------ end pdftk burst
  292. LOG("runpdfTeX ... ");
  293. runpdfTeX( "$path$name", $name );
  294. LOG("all finished ... ");
  295.  
  296. # Save preable
  297. sub savePreamble {
  298.     my $filename = pop;
  299.     LOG("----- Start Preamble -----");
  300.     open my $FILEp, '>', "$tempDir/$filename.preamble";
  301.     open my $FILE,  '<', "$name.tex";
  302.     while (<$FILE>) {
  303.         my $i = index( $_, "begin{document}\n" );
  304.         if ( $i > 0 ) {
  305.             if ( $i > 1 ) { print $FILEp substr( $_, 0, --$i ); }
  306.             if ($single) {
  307.             print $FILEp "\\newenvironment{tikzexport}{}{}\n";
  308.           print $FILEp "\\pagestyle{empty}\n";
  309.             }
  310.             close $FILEp;
  311.             LOG("----- Close Preamble ------");
  312.             return;
  313.         }
  314.         else {
  315.             print $FILEp "$_";
  316.             LOG("$_");
  317.         }
  318.     }
  319.  
  320.     close $FILE;
  321.     close $FILEp;
  322.     if ($Verbose) { LOG("<-----Preamble<----"); }
  323.     return;
  324. }
  325.  
  326. sub searchTiKZ {                                       
  327.   my @TiKZ = ();                                       
  328.   my @TiKZtotal = ();                  
  329.   my $depth = -1;                                      
  330.   my $type = -1;                                       
  331.   my $EndDocument = 0;         
  332.   my $iVerb = 0;                                       
  333.   open my $FILE, '<', "$name.tex";
  334.   while (<$FILE>) {                            
  335.     if (!$EndDocument) {
  336.     chomp;                                                       
  337.     my $line = $_;                             
  338.     if ( !$iVerb ) {
  339.  $iVerb = ((index($line,"begin{verbatim*}") > 0) or (index($line,"begin{verbatim}") > 0) or (index($line,"begin{lstlisting}") > 0) or (index($line,"begin{Verbatim}") > 0));
  340.     }                                                          
  341.     if ( !$iVerb ) {
  342.       my $iTiKE = index($line,"begin{tikzexport}");
  343.       my $iTiKZ = index($line,"begin{tikzpicture}");
  344.       if ($iTiKZ < 0) { $iTiKZ = index($line,"begin{dependency}"); }
  345.         if ($iTiKZ < 0) { $iTiKZ = index($line,"begin{circuitikz}"); }
  346.         if ($iTiKZ < 0) { $iTiKZ = index($line,"begin{tikzcd}"); }
  347.         if ($iTiKZ < 0) { $iTiKZ = index($line,"begin{ganttchart}"); }
  348.         if (($iTiKE > 0) && ( $type == 1 )){ print "tikzexport environment must be of outer level!\n"; exit 1; }
  349.       if ( $type < 0 ) {                       
  350.         if ($iTiKE > 0) {              
  351.           $type = 2;                   
  352.           $line = substr($line,$iTiKE-1);      
  353.           LOG("TikZ -line: $line");
  354.         }                              
  355.         elsif ( $iTiKZ > 0 ) {
  356.           $type = 1;
  357.           $depth++;  
  358.           $line = substr($line,$iTiKZ-1);      
  359.           LOG("TiKE-line: $line");
  360.         }
  361.       }
  362. #
  363.       if ($type > 0) {                                 
  364.       LOG ("searchTiKZ: set \$type=$type");
  365.       $iTiKZ = index($line,"end{tikzpicture}");
  366.       if ($iTiKZ < 0) { $iTiKZ = index($line,"end{tikzcd}"); }
  367.         if ($iTiKZ < 0) { $iTiKZ = index($line,"end{dependency}"); }
  368.       if ($iTiKZ < 0) { $iTiKZ = index($line,"end{circuitikz}"); }
  369.         if ($iTiKZ < 0) { $iTiKZ = index($line,"end{ganttchart}"); }
  370.       $iTiKE = index($line,"end{tikzexport}"); 
  371.       if ($iTiKZ > 0) {                        
  372.       if ( $type < 2) {                
  373.             LOG ("searchTiKZ: $line");
  374.             $depth--;
  375.             if ($depth < 0) {
  376.               $type = -1;
  377.               if (index($line,"end{tikzcd}") > 0)      
  378.            {push @TiKZ,substr($line,0,$iTiKZ+11); }
  379.                 if (index($line,"end{circuitikz}") > 0)        
  380.            {push @TiKZ,substr($line,0,$iTiKZ+15); }
  381.             if (index($line,"end{tikzpicture}") > 0)
  382.               { push @TiKZ,substr($line,0,$iTiKZ+16); }
  383.                 if (index($line,"end{dependency}") > 0)
  384.             { push @TiKZ,substr($line,0,$iTiKZ+15); }
  385.                 if (index($line,"end{ganttchart}") > 0)
  386.             { push @TiKZ,substr($line,0,$iTiKZ+15); }
  387.             LOG ("searchTiKZ: set \$type=$type");
  388.              push @TiKZtotal,[@TiKZ];  
  389.       LOG ("---->TikZ---->\n@TiKZ\n<----TikZ<----");
  390.               @TiKZ = ();                      
  391.             }                          
  392.           } else { push @TiKZ,$line; } 
  393.         } elsif ($iTiKE > 0) {         
  394.           LOG ("searchTiKZ: $line");
  395.           $type = -1;
  396.           push @TiKZ,substr($line,0,$iTiKE+15);
  397.           LOG ("searchTiKZ: set \$type=$type");
  398.           push @TiKZtotal,[@TiKZ];     
  399.           LOG ("---->tikzexp---->\n@TiKZ\n<----tikzexp<----");
  400.           @TiKZ =();   
  401.         } else { push @TiKZ,$line; }    # add line
  402.       }
  403.       my $i = index($line,"end{document}");
  404.       if ($i > 0) { $EndDocument++; LOG("EndDocument in searchTiKZ"); }
  405.     }                          
  406.     if ((index($line,"end{verbatim*}") > 0) or ( index($line,"end{verbatim}") > 0 ) or ( index($line,"end{lstlisting}") > 0 ) or (index($line,"end{Verbatim}") > 0 )) { $iVerb = 0; }
  407.   }}
  408.   if ( $Verbose ) {
  409.     LOG("---->TikZtotal---->");
  410.     for my $aref ( @TiKZtotal ) {
  411.       my @a = @$aref;
  412.       my $i = 1;
  413.                         foreach ( @a ) { LOG ($a[$i]); $i=$i+1; }
  414.     }
  415.     LOG ("<----tikzotal<----");
  416.   }
  417.   close $FILE;
  418.   return @TiKZtotal;
  419. }
  420. # Creating files, eps, pdf and ppm for images
  421. if ($single) {
  422.     sub runFORCE{
  423.     my $filename = pop;
  424.                 if($xetex){
  425.         if($miktex){
  426.         system("xelatex -enable-write18 -interaction=batchmode $tempDir/$filename-tikz");}
  427.         else {
  428.         system("xelatex -shell-escape -interaction=batchmode $tempDir/$filename-tikz");}
  429.         system("pdfcrop -xetex -margin 2 $tempDir/$filename-tikz.pdf $imageDir/$filename-tikz-$imgNo.pdf");
  430.                                 }
  431.         elsif($luatex){
  432.         if($miktex){
  433.         system("lualatex -enable-write18 -interaction=batchmode $tempDir/$filename-tikz");}
  434.         else {
  435.         system("lualatex -shell-escape -interaction=batchmode $tempDir/$filename-tikz");}
  436.         system("pdfcrop -luatex -margin 2 $tempDir/$filename-tikz.pdf $imageDir/$filename-tikz-$imgNo.pdf");
  437.                 }
  438.                 else{
  439.         if($miktex){
  440.         system("pdflatex -enable-write18 -interaction=batchmode $tempDir/$filename-tikz");}
  441.         else {
  442.         system("pdflatex -shell-escape -interaction=batchmode $tempDir/$filename-tikz");}
  443.         system("pdfcrop -margin 2 $tempDir/$filename-tikz.pdf $imageDir/$filename-tikz-$imgNo.pdf");
  444.                                 }
  445.                                
  446.                 if($files){
  447.         copy( "$filename-tikz.tex", "$imageDir/$filename-tikz-$imgNo.tex" );}
  448.                 if($eps){
  449.         system("pdftops -level3 -eps $imageDir/$filename-tikz-$imgNo.pdf $imageDir/$filename-tikz-$imgNo.eps");}
  450.     if ($ppm) {
  451.         system("pdftoppm -r $DPI $imageDir/$filename-tikz-$imgNo.pdf $imageDir/$filename-tikz-$imgNo");}
  452.     $imgNo = $imgNo + 1;
  453.     }
  454. }
  455. else {
  456. # Creating files and eps for images
  457.     sub runTeX {
  458.     my $filename = pop;
  459.     if ($eps) {
  460.         system("pdftops -level3 -eps $imageDir/$filename-$imgNo.pdf $imageDir/$filename-$imgNo.eps");}
  461.     if ($files) {
  462.         copy( "$filename.tex", "$imageDir/$filename-$imgNo.tex" );}
  463.     $imgNo = $imgNo + 1;
  464.     }
  465. }
  466. sub runFile {
  467.   my $filename = pop;
  468.   my @TiKZarray = searchTiKZ();
  469.   if ( $Verbose ) {
  470.     LOG("---->TiKZarray---->");
  471.     for my $aref ( @TiKZarray ) {
  472.       my @a = @$aref;
  473.       my $i = 1;
  474.       foreach ( @a ) { print LOG $a[$i]."\n"; $i=$i+1; }
  475.     }
  476.     LOG("<----TiKZarray<----");
  477.     my $no = @TiKZarray;
  478.     LOG("TiKZ: ".$no." TiKZ sequence(s)");
  479.   }
  480.   for my $aref ( @TiKZarray ) {
  481.     my @TiKZ = @$aref;
  482.     open my $FILEp,'<',"$tempDir/$filename.preamble";
  483.     open my $FILEsub,'>',"$tempDir/$filename-tikz.tex";
  484.     while (<$FILEp>) {print $FILEsub $_; }
  485.                 print $FILEsub "\\begin{document}\n";
  486.                 if ( $Verbose ) { LOG("\@TiKZ: $_"); }
  487.     foreach ( @TiKZ ) { print $FILEsub "$_\n"; }
  488.     print $FILEsub "\\end{document}";
  489.     close $FILEsub;
  490.     close $FILEp;
  491.                 if ($single) {
  492.                 runFORCE("$name");
  493.                 }
  494.                 else{
  495.     runTeX("$tempDir/$name-tikz");
  496.   }
  497. }
  498. }
  499. # Renaming ppm need for correct name
  500. if (!$noImages){
  501. my $dren = "$tempDir/$imageDir";
  502. my $fichero = '';
  503. my $ppmren = '';
  504. my $renNo = 1;
  505. if(opendir(DIR,$dren)){
  506. foreach (readdir DIR){
  507.        $fichero = $_;
  508.         if ( $fichero =~ /($name-tikz-)(\d+|\d+[-]\d+).ppm/) {
  509.       my $renNo   = int($2);
  510.       my $newname="$1$renNo.ppm";
  511.       $ppmren = rename("$dren/$fichero","$dren/$newname");
  512.         }
  513.         }
  514. }
  515. closedir DIR;
  516. }
  517. #----------------------- Replace files ----------------
  518. sub runpdfTeX() {
  519.   my ($name,$pdfname) = @_;
  520.   open my $PDF,'>',"$tempDir/$pdfname-pdf.tex";
  521.   open my $FILE,'<',"$name.tex";
  522.   my $ignore = 0;
  523.   my $IMGno = 1;
  524.   my $depth = -1;
  525.   my $type = -1;
  526.   my $EndDocument = 0;
  527.   my $iVerb = 0;
  528.   while (<$FILE>) {            
  529.     if ( !$iVerb ) {
  530.       $iVerb = ((index($_,"begin{verbatim*}") > 0) or (index($_,"begin{verbatim}") > 0) or (index($_,"begin{lstlisting}") > 0) or (index($_,"begin{Verbatim}") > 0));
  531.     }
  532.     if ( !$iVerb ) {
  533.       my $i = index($_,"end{document}");
  534.       if ($i > 0) { print $PDF $_; $EndDocument++; LOG("EndDocument in runpdfTeX"); }
  535.       if ( !$EndDocument ) {
  536.         my $iTiKE = index($_,"begin{tikzexport}");
  537.         if ( $iTiKE > 0 ) {
  538.           $type = 2;
  539.           $ignore = 1;
  540.           if ($iTiKE > 1) { print $PDF substr($_,0,--$iTiKE); }
  541.         print $PDF "\\includegraphics[scale=$Iscale]{$pdfname-tikz-$IMGno}";
  542.           $IMGno=$IMGno+1;
  543.         }      
  544.         if ( $type < 2 ) {
  545.           my $iTiKZ = index($_,"begin{tikzpicture}");
  546.       if ($iTiKZ < 0) { $iTiKZ = index($_,"begin{tikzcd}"); }
  547.         if ($iTiKZ < 0) { $iTiKZ = index($_,"begin{dependency}"); }    
  548.       if ($iTiKZ < 0) { $iTiKZ = index($_,"begin{circuitikz}"); }
  549.         if ($iTiKZ < 0) { $iTiKZ = index($_,"begin{ganttchart}"); }
  550.       if ( $iTiKZ >= 0 ) {
  551.             $ignore = 1;
  552.             $type = 1;
  553.             $depth++;                          
  554.             LOG("Increase depth: $depth");
  555.       if ( $depth == 0 ) {
  556.       if ($iTiKZ > 1) { print $PDF substr($_,0,--$iTiKZ); }
  557.       print $PDF "\\includegraphics[scale=$Iscale]{$pdfname-tikz-$IMGno}";
  558.       $IMGno=$IMGno+1;
  559.          LOG("Increase Image counter: $IMGno");
  560.             }
  561.           }
  562.         }
  563.         if ( !$ignore ) { print $PDF "$_"; }   
  564.         if ( $type == 2 ) {    
  565.           my $iTiKE = index($_,"end{tikzexport}");
  566.           if ($iTiKE > 0) {
  567.             print $PDF substr($_,$iTiKE+15);
  568.             $ignore = 0;
  569.             $type=-1;
  570.           }                                            
  571.         } elsif ( $type == 1 ) {       
  572.       my $iTiKZ = index($_,"end{tikzpicture}");
  573.       if ($iTiKZ < 0) { $iTiKZ = index($_,"end{dependency}"); }
  574.       if ($iTiKZ < 0) { $iTiKZ = index($_,"end{tikzcd}"); }
  575.         if ($iTiKZ < 0) { $iTiKZ = index($_,"end{circuitikz}"); }
  576.         if ($iTiKZ < 0) { $iTiKZ = index($_,"end{ganttchart}"); }
  577.       if ($iTiKZ > 0) {
  578.       if (index($_,"end{tikzpicture}") > 0)
  579.                     { print $PDF substr($_,$iTiKZ+16); }       
  580.         if (index($_,"end{dependency}") > 0)
  581.         { print $PDF substr($_,$iTiKZ+15); }   
  582.         if (index($_,"end{tikzcd}") > 0)
  583.         { print $PDF substr($_,$iTiKZ+11); }   
  584.         if (index($_,"end{circuitikz}") > 0)
  585.         { print $PDF substr($_,$iTiKZ+15); }
  586.         if (index($_,"end{ganttchart}") > 0)
  587.       { print $PDF substr($_,$iTiKZ+15); }
  588.       $depth--;
  589.       LOG("Decrease depth: $depth");
  590.       if ($depth < 0) { $ignore = 0; }
  591.           }
  592.         }
  593.       }
  594.     }
  595.    else { print $PDF $_; }
  596.     if ((index($_,"begin{verbatim*}") > 0) or ( index($_,"end{verbatim}") > 0 ) or ( index($_,"end{lstlisting}") > 0 ) or ( index($_,"end{Verbatim}") > 0 )) { $iVerb = 0; }
  597.   }
  598.   close $FILE;
  599.   close $PDF;
  600. # --------------- Adding lines in preamble ----------------------
  601.         open my $IPDF,'<', "$tempDir/$pdfname-pdf.tex";
  602.         undef $/;   # read all file
  603.         my ($uno,$dos) = split(/\\begin\{document\}/,<$IPDF>,2);
  604.         close $IPDF;
  605.         my @coment = split /\n/, $uno;
  606.         my @preamb;
  607.         foreach my $line (@coment) {
  608.         chomp($line);
  609.         $line =~ s/\\usepackage(?:\[.+?\])?\{grfext\}//g;      
  610.         $line =~ s/\\PrependGraphicsExtensions\*\{.+?\}//g;    
  611.         $line =~ s/(\\usepackage(?:\[.+?\])?)\{graph/\%$1\{graph/g;
  612.         $line =~ s/(\\graphicspath)\{\{/\%$1\{\{/g;
  613.         next if $line =~ m/^\s*$/;
  614.         push(@preamb,$line);
  615.   }
  616. my $clean = join("\n", @preamb, "\\usepackage{grfext}\n\\\PrependGraphicsExtensions*{$Iext}\n\\usepackage{graphicx}\n\\graphicspath{{$imageDir/}}\n\\begin{document}". $dos);
  617.  
  618. open my $OPDF,'>',"$tempDir/$pdfname-pdf.tex";
  619. print $OPDF $clean;
  620. close $OPDF;
  621. #------------------------- Compiled final file --------------------------
  622. if ($norun) { print "Done\n"; }
  623. else{
  624. if ($xetex) {
  625.     system("xelatex -interaction=batchmode $tempDir/$pdfname-pdf.tex");}
  626. elsif ($luatex) {
  627.     system("lualatex -interaction=batchmode $tempDir/$pdfname-pdf.tex");}
  628. else {
  629. system("pdflatex -interaction=batchmode $tempDir/$pdfname-pdf.tex");}
  630. print "Done\n";
  631. }
  632. if ($ppm){
  633.      print "If you need to create jpg/png/svg type cd $imageDir and run\n";
  634.      print "mogrify -format [ext] *.ppm\n";
  635.         }
  636. }
  637. #----------------Clear Temp files -----------------------------
  638. if ($clear) {
  639.                                 if ($norun){}  
  640.         if ($single) {
  641.             unlink "$tempDir/$name-tikz.pdf";
  642.             unlink "$tempDir/$name-tikz.aux";
  643.             unlink "$tempDir/$name-tikz.log";
  644.             unlink "$tempDir/$name-tikz.tex";
  645.                 unlink "$tempDir/$name.plog";
  646.                 unlink "$tempDir/$name.preamble";
  647.                 unlink "$tempDir/$name-pdf.aux";
  648.                 unlink "$tempDir/$name-pdf.log";
  649.                                         }
  650.         else {
  651.             unlink "$tempDir/$name.plog";
  652.             unlink "$tempDir/$name.preamble";
  653.             unlink "$tempDir/$name-pdf.aux";
  654.             unlink "$tempDir/$name-pdf.log";
  655.             unlink "$tempDir/$name-pics.pdf";
  656.             unlink "$tempDir/$name-pics.tex";
  657.             unlink "$tempDir/$name-pics.aux";
  658.             unlink "$tempDir/$name-pics.log";
  659.                 unlink "$tempDir/$name-tikz.tex";
  660.                                         }
  661.         }
  662. sub LOG() {
  663.     if ($Verbose) { print $LOGfile "@_\n"; }
  664. }
  665. __END__
Coloreado en 0.018 segundos, usando GeSHi 1.0.8.4
y aquí comienzan mis consultas:

1. En varias partes del código (como en las lineas 344-348) utilizo varios if de forma consecutiva, ¿debo cambiarlos por elsif?

2. Tengo líneas (como la 339) que son muy largas, ¿puedo dividirlas en dos? (como un quiebre o salto de línea, sólo por estética)

Y la última gran duda (y la que originó este hilo):
Basicamente el script trabaja en dos formas
a) (por defecto) crea una copia del archivo cargando unas líneas al inicio y luego hace un par de llamadas a sistema dependiendo de las opciones

b) (modo single) lee todo el archivo, extrae los bloques de texto que necesito, los graba en archivos individuales y luego hace las llamadas a sistema dependiendo de las opciones.

Me gustaría saber si puedo crear un archivo (nuevo) que contenga todos los bloques de texto que necesito separados por la linea \newpage a excepción del último, que debe finalizar con \end{document}, es decir, copiar filename.preamble, añadir un par de líneas y todos los elementos del array que contiene los bloques de texto (separados por \newpage) terminando con la línea \end{document}:
Sintáxis: [ Descargar ] [ Ocultar ]
Using text Syntax Highlighting
  1. filename.preamble
  2. \newenvironment{tikzexport}{}{}
  3. \begin{document}
  4. bloque array 1
  5. \newpage
  6. bloque array 2
  7. \newpage
  8. bloque array 3
  9. \newpage
  10. ...
  11. \bloque array n
  12. \end{document}
Coloreado en 0.000 segundos, usando GeSHi 1.0.8.4
¿Cómo puedo logar esto?

De antemano agradecido por la ayuda.
Pablo.
pablgonz
Perlero nuevo
Perlero nuevo
 
Mensajes: 236
Registrado: 2010-09-08 21:03 @919
Ubicación: Concepción (Chile)

Publicidad

Re: Duda con elsif, quiebre de línea y array en script

Notapor explorer » 2012-03-29 07:20 @347

pablgonz escribiste:1. En varias partes del código (como en las lineas 344-348) utilizo varios if de forma consecutiva, ¿debo cambiarlos por elsif?
Si son disyuntivas y no tienen efectos colaterales, sí. Disyuntivas: cada condición abarca una parte del espacio de búsqueda, y no se solapan. Efectos colaterales: la acción de una condición verdadera no afectará a los resultados de las siguientes condiciones.)

En tu caso, en las líneas 344 a 348, sí que hay efectos colaterales: la acción de una condición verdadera afectará al resultado de las condiciones posteriores. Por lo tanto, no puedes poner elsif().
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1.         if ($iTiKZ < 0) { $iTiKZ = index($line, "begin{dependency}"); }
  2.         if ($iTiKZ < 0) { $iTiKZ = index($line, "begin{circuitikz}"); }
  3.         if ($iTiKZ < 0) { $iTiKZ = index($line, "begin{tikzcd}"    ); }
  4.         if ($iTiKZ < 0) { $iTiKZ = index($line, "begin{ganttchart}"); }
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4


pablgonz escribiste:2. Tengo líneas (como la 339) que son muy largas, ¿puedo dividirlas en dos? (como un quiebre o salto de línea, sólo por estética)
Sí, se puede poner de muchas maneras.

Esto es lo que me da, de forma automática, perltidy, a lo que he añadido un par de espacios al final, para que quede más bonito:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1.         $iVerb = (
  2.                    ( index( $line, "begin{verbatim*}"  ) > 0 )
  3.                 or ( index( $line, "begin{verbatim}"   ) > 0 )
  4.                 or ( index( $line, "begin{lstlisting}" ) > 0 )
  5.                 or ( index( $line, "begin{Verbatim}"   ) > 0 )
  6.         );
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4



pablgonz escribiste:Me gustaría saber si puedo crear un archivo (nuevo) que contenga todos los bloques de texto que necesito separados por la linea \newpage a excepción del último, que debe finalizar con \end{document}, es decir, copiar filename.preamble, añadir un par de líneas y todos los elementos del array que contiene los bloques de texto (separados por \newpage) terminando con la línea \end{document} ¿Cómo puedo logar esto?
Es una pregunta difícil, pues implica que hay que leer y entender todo el programa. Yo ahora mismo no tengo tiempo para eso. Quizás otro forero lo pueda hacer.
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: Duda con elsif, quiebro de línea y array en script

Notapor pablgonz » 2012-03-29 21:17 @928

Mucha gracias por la aclaración de mis dudas
explorer escribiste:Es una pregunta difícil, pues implica que hay que leer y entender todo el programa. Yo ahora mismo no tengo tiempo para eso. Quizás otro forero lo pueda hacer.
Trataré de explicarme un poco. Si el fichero de entrada es este:
Sintáxis: [ Descargar ] [ Ocultar ]
Using latex Syntax Highlighting
  1. \documentclass{article}
  2. \usepackage{pgf,tikz}
  3. \begin{document}
  4. Hola
  5. \begin{tikzpicture}
  6. \pgfmathsetmacro{\b}{75}
  7. \end{tikzpicture}
  8. Como
  9. \begin{tikzpicture}[domain=0:4]
  10. \draw[color=blue] plot[id=sin] function{sin(x)}
  11. node[right] {$f(x) = \sin x$};
  12. \draw[color=orange] plot[id=exp] function{0.05*exp(x)}
  13. node[right] {$f(x) = \frac{1}{20} \mathrm e^x$};
  14. \end{tikzpicture}
  15. estan
  16. \begin{tikzexport}
  17. Perl
  18. \end{tikzexport}
  19. \end{document}
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4
el script lo lee y extrae todos los entornos tikzpicture, tikzexport (y otro que tengo definidos), ignorando esto si estan dentro de otros entornos (también definidos).
Al trabajar en modo single (sub runFILE) el script crea un archivo individual con el contenido de cada entorno
Sintáxis: [ Descargar ] [ Ocultar ]
Using latex Syntax Highlighting
  1. \documentclass{article}
  2. \usepackage{pgf,tikz}
  3. \begin{document}
  4. \begin{tikzpicture}
  5. \pgfmathsetmacro{\b}{75}
  6. \end{tikzpicture}
  7. \end{document}
Coloreado en 0.000 segundos, usando GeSHi 1.0.8.4
Sintáxis: [ Descargar ] [ Ocultar ]
Using latex Syntax Highlighting
  1. \documentclass{article}
  2. \usepackage{pgf,tikz}
  3. \begin{document}
  4. \begin{tikzpicture}[domain=0:4]
  5. \draw[color=blue] plot[id=sin] function{sin(x)}
  6. node[right] {$f(x) = \sin x$};
  7. \draw[color=orange] plot[id=exp] function{0.05*exp(x)}
  8. node[right] {$f(x) = \frac{1}{20} \mathrm e^x$};
  9. \end{tikzpicture}
  10. \end{document}
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4
Sintáxis: [ Descargar ] [ Ocultar ]
Using latex Syntax Highlighting
  1. \documentclass{article}
  2. \usepackage{pgf,tikz}
  3. \begin{document}
  4. \begin{tikzexport}
  5. Perl
  6. \end{tikzexport}
  7. \end{document}
Coloreado en 0.000 segundos, usando GeSHi 1.0.8.4

Lo que deseo hacer es modificar o crear otra subrutina u opción, que me cree un fichero (name-img.tex, por ejemplo) pero que contenga todos los entornos, separados por \newpage, como esto:
Sintáxis: [ Descargar ] [ Ocultar ]
Using latex Syntax Highlighting
  1. \documentclass{article}
  2. \usepackage{pgf,tikz}
  3. \pagestyle{empty}
  4. \begin{document}
  5. \begin{tikzpicture}
  6. \pgfmathsetmacro{\b}{75}
  7. \end{tikzpicture}
  8. \newpage
  9. \begin{tikzpicture}[domain=0:4]
  10. \draw[color=blue] plot[id=sin] function{sin(x)}
  11. node[right] {$f(x) = \sin x$};
  12. \draw[color=orange] plot[id=exp] function{0.05*exp(x)}
  13. node[right] {$f(x) = \frac{1}{20} \mathrm e^x$};
  14. \end{tikzpicture}
  15. \newpage
  16. \begin{tikzexport}
  17. Perl
  18. \end{tikzexport}
  19. \end{document}
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4


Por ahora (y por eso la duda) creo los archivos individuales (con la opción -f) y luego (con otro script varias líneas a mano) borro lo que no necesito y añado \newpage y creo un único fichero.

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

Re: Duda con elsif, quiebro de línea y array en script

Notapor explorer » 2012-03-30 17:37 @776

A ver...

Por lo que veo... consiste en leer los archivos individuales, quitarles la cabecera y el pie, unirlos con \newpage, y agregarles una cabecera y un nuevo pie...

No parece complicado. ¿No?

El problema es cómo integrar todo esto en el programa actual.

La primera pregunta sería si, a esa subrutina, se le pueden entregar los entornos tal cual los estás grabando a los archivos individuales.

La parte más difícil que veo es lo que dices que hay entornos unos dentro de otros, y eso puede complicar mucho el análisis.

Esta es una manera de resolver el caso más sencillo. Dado este fichero de entrada:
Sintáxis: [ Descargar ] [ Ocultar ]
Using latex Syntax Highlighting
  1. \documentclass{article}
  2. \usepackage{pgf,tikz}
  3. \begin{document}
  4. Hola
  5. \begin{tikzpicture}
  6. \pgfmathsetmacro{\b}{75}
  7. \end{tikzpicture}
  8. Como
  9. \begin{tikzpicture}[domain=0:4]
  10. \draw[color=blue] plot[id=sin] function{sin(x)}
  11. node[right] {$f(x) = \sin x$};
  12. \draw[color=orange] plot[id=exp] function{0.05*exp(x)}
  13. node[right] {$f(x) = \frac{1}{20} \mathrm e^x$};
  14. \end{tikzpicture}
  15. estan
  16. \begin{tikzexport}
  17. Perl
  18. \end{tikzexport}
  19. \end{document}
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4
con este programa:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. #!/usr/bin/perl
  2. use autodie;                    # es mejor morir que regresar con deshonor (proverbio Klingon)
  3. use strict;
  4. use warnings;
  5. use diagnostics;
  6.  
  7. open my $LATEX, '<', 'code_30327.txt';
  8.  
  9. my $estamos_en = 'la_cabecera';
  10.  
  11. while (<$LATEX>) {
  12.     if ($estamos_en eq 'la_cabecera') {
  13.         if (/^\\begin\{document\}/) {
  14.             $estamos_en = 'documento';
  15.             print "\\pagestyle{empty}\n";
  16.             print;
  17.         }
  18.     }
  19.    
  20.     if (/^\\begin\{(?:tikzpicture|tikzexport)\}/) {
  21.         if ($estamos_en eq 'fin_rango') {
  22.             print "\\newpage\n";
  23.         }
  24.         $estamos_en = 'rango';
  25.     }
  26.  
  27.     if (/^\\end\{(?:tikzpicture|tikzexport)\}/) {
  28.         $estamos_en = 'fin_rango';
  29.         print;
  30.     }
  31.  
  32.     if ($estamos_en eq 'la_cabecera'
  33.      or $estamos_en eq 'rango'
  34.     ) {
  35.         print;
  36.     }
  37. }
  38. close   $LATEX;
  39.  
  40. print "\\end{document}\n";
  41.  
  42. __END__
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4
obtenemos
Sintáxis: [ Descargar ] [ Ocultar ]
Using latex Syntax Highlighting
  1. \documentclass{article}
  2. \usepackage{pgf,tikz}
  3. \pagestyle{empty}
  4. \begin{document}
  5. \begin{tikzpicture}
  6. \pgfmathsetmacro{\b}{75}
  7. \end{tikzpicture}
  8. \newpage
  9. \begin{tikzpicture}[domain=0:4]
  10. \draw[color=blue] plot[id=sin] function{sin(x)}
  11. node[right] {$f(x) = \sin x$};
  12. \draw[color=orange] plot[id=exp] function{0.05*exp(x)}
  13. node[right] {$f(x) = \frac{1}{20} \mathrm e^x$};
  14. \end{tikzpicture}
  15. \newpage
  16. \begin{tikzexport}
  17. Perl
  18. \end{tikzexport}
  19. \end{document}
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4
que es lo solicitado, pero su lógica es un poco endeble... fallará si el documento de partida es algo más complejo...
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: Duda con elsif, quiebro de línea y array en script

Notapor pablgonz » 2012-04-01 19:51 @868

Gracias por la respuesta explorer, le daré un vistazo a tu propuesta, y trataré de adaptarlo. Quizás deba crear todos los sub ficheros (con -f) primero, luego leer el directorio donde están y unirlos (con esto evito lo de entorno dentro de entorno).

Me haré algo de tiempo y veré cómo puedo resolverlo.
Saludos
Pablo
pablgonz
Perlero nuevo
Perlero nuevo
 
Mensajes: 236
Registrado: 2010-09-08 21:03 @919
Ubicación: Concepción (Chile)


Volver a Básico

¿Quién está conectado?

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

cron