• Publicidad

Expresión regular para texto anidado

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

Re: Expresión regular para texto anidado

Notapor pablgonz » 2014-12-19 14:16 @636

Gracias por la explicación, dejaré la división como estaba. Ahora sí, la última, para cerrar el tema de los anidados, estoy tratando de capturar:
Sintáxis: [ Descargar ] [ Ocultar ]
Using latex Syntax Highlighting
  1. \tikzset{
  2.  pics/.cd,
  3.  disc/.style = {
  4.    code = {
  5.      \fill [white] ellipse [x radius = 2, y radius = 2/3];
  6.      \path [left color = black!50, right color = black!50,
  7.        middle color = black!25]
  8.        (-2+.05,-1.1) arc (180:360:2-.05 and 2/3-.05*2/3) -- cycle;
  9.      \path [top color = black!25, bottom color = white]
  10.        (0,.05*2/3) ellipse [x radius = 2-.05, y radius = 2/3-.05*2/3];
  11.      \path [left color = black!25, right color = black!25,
  12.        middle color = white] (-2,0) -- (-2,-1) arc (180:360:2 and 2/3)
  13.        -- (2,0) arc (360:180:2 and 2/3);
  14.      \foreach \r in {225,315}
  15.         \foreach \i [evaluate = {\s=30;}] in {0,2,...,30}
  16.           \fill [black, fill opacity = 1/50]
  17.             (0,0) -- (\r+\s-\i:2 and 2/3) -- ++(0,-1)
  18.             arc (\r+\s-\i:\r-\s+\i:2 and 2/3) -- ++(0,1) -- cycle;
  19.       \foreach \r in {45,135}
  20.         \foreach \i [evaluate = {\s=30;}] in {0,2,...,30}
  21.           \fill [black, fill opacity = 1/50]
  22.             (0,0) -- (\r+\s-\i:2 and 2/3)
  23.             arc (\r+\s-\i:\r-\s+\i:2 and 2/3)  -- cycle;
  24.     }
  25.   },
  26.   disc bottom/.style = {
  27.    code = {
  28.      \foreach \i in {0,2,...,30}
  29.         \fill [black, fill opacity = 1/60] (0,-1.1)
  30.           ellipse [x radius = 2+\i/40, y radius = 2/3+\i/60];
  31.       \path pic {disc};
  32.     }
  33.   }
  34. }
  35.  
  36. \begin{tikzpicture}
  37. \path (0,0) pic {disc bottom} (0,1.25) pic {disc} (0,2.5) pic {disc};
  38. \end{tikzpicture}
Coloreado en 0.002 segundos, usando GeSHi 1.0.8.4

dentro de \begin{postscript} ... \end{postscript} usando:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. my $BPL = '\begin{postscript}';
  2. my $EPL = '\end{postscript}';
  3. $cuerpo =~ s/((\\tikzset\{[^\}]+\})?\s*\\begin\{tikzpicture\}.*?\\end\{tikzpicture\})/$BPL\n$1\n$EPL/gmsx;
Coloreado en 0.002 segundos, usando GeSHi 1.0.8.4

pero no lo logro, al parecer son muchos {...} dentro de \tikzset para capturarlos de forma opcional.
Agradecido por todas las explicaciones y soluciones brindadas.
Saludos.
Pablo
pablgonz
Perlero nuevo
Perlero nuevo
 
Mensajes: 236
Registrado: 2010-09-08 21:03 @919
Ubicación: Concepción (Chile)

Publicidad

Re: Expresión regular para texto anidado

Notapor explorer » 2014-12-19 15:07 @671

Sería algo así, pero no lo he probado.
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. $cuerpo =~ s/(\\tikzset\{.*?\\end\{tikzpicture\}\n)/$BPL\n$1\n$EPL/gms;
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: 14476
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España

Re: Expresión regular para texto anidado

Notapor pablgonz » 2014-12-20 00:32 @064

Vale, al final me decidí por dejar esta línea:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. $cuerpo =~ s/((\\tikzset(\{(?:\{.*\}|[^\{])*\}).*?)?\\begin\{tikzpicture\}.*?\\end\{tikzpicture\})/$BPL\n$1\n$EPL/gmsx;
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4
Última edición por explorer el 2014-12-20 05:57 @290, editado 1 vez en total
Razón: ésta => esta
pablgonz
Perlero nuevo
Perlero nuevo
 
Mensajes: 236
Registrado: 2010-09-08 21:03 @919
Ubicación: Concepción (Chile)

Re: Expresión regular para texto anidado

Notapor explorer » 2014-12-20 06:07 @297

Para aumentar la velocidad, es mejor que definas los paréntesis que no quieres capturar como '(?:...)'. Sí que lo tienes hecho en uno de ellos, pero veo que hay dos pares de paréntesis que también puedes marcar así.
JF^D Perl programming & Raku programming. Grupo en Telegram: https://t.me/Perl_ES
Avatar de Usuario
explorer
Administrador
Administrador
 
Mensajes: 14476
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España

Re: Expresión regular para texto anidado

Notapor pablgonz » 2014-12-20 10:04 @461

¿Algo así?
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. $cuerpo =~ s/
  2.         (
  3.             (?:\\tikzset(\{(?:\{.*\}|[^\{])*\}).*?)? # si está lo guardo
  4.             (?:\\begin\{tikzpicture\}) # aquí comienza la búsqueda
  5.                     .*?                # guardo el contenido en $1
  6.             (?:\\end\{tikzpicture\})   # termina la búsqueda
  7.         ) # cierra $1
  8.         /$BPL\n$1\n$EPL/gmsx;
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4
pablgonz
Perlero nuevo
Perlero nuevo
 
Mensajes: 236
Registrado: 2010-09-08 21:03 @919
Ubicación: Concepción (Chile)

Re: Expresión regular para texto anidado

Notapor explorer » 2014-12-20 16:44 @739

Sí.

Una cosa más. El patrón \{.*\} es casi mejor ponerlo así: \{.*?\}

Así, el comodín termina en pares de llaves, ocupando el tamaño mínimo.
JF^D Perl programming & Raku programming. Grupo en Telegram: https://t.me/Perl_ES
Avatar de Usuario
explorer
Administrador
Administrador
 
Mensajes: 14476
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España

Re: Expresión regular para texto anidado

Notapor pablgonz » 2014-12-21 18:06 @796

explorer escribiste:... El patrón \{.*\} es casi mejor ponerlo así: \{.*?\}
Gracias, lo he cambiado por lo que propones. Una consulta más, ¿cómo niego una palabra en una expresión regular?, es decir, quiero aplicar:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1.     $cuerpo =~ s/
  2.             (
  3.                 (?:\\tikzset(\{(?:\{.*?\}|[^\{])*\}).*?)? # si está lo guardo
  4.                 (?:\\begin\{tikzpicture\}) # aquí comienza la búsqueda
  5.                         .*?                # guardo el contenido en $1
  6.                 (?:\\end\{tikzpicture\})   # termina la búsqueda
  7.             ) # cierra $1
  8.             /$BPL\n$1\n$EPL/gmsx;
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4

solo si no está entre \begin{postscript} ... \end{postscript}. Me he cabeceado un buen rato y no he podido dar con la línea correcta. Intenté con (?<=\begin{postscript}) y con (?<!\begin{postscript}) pero no funcionó.

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

Re: Expresión regular para texto anidado

Notapor explorer » 2014-12-21 18:40 @819

La cosa se complica, ¿eh? :)

Puede llegar un momento en que sea más fácil atacar el problema de otra manera. Por ejemplo, procesar el archivo línea a línea, con banderas. O usar una representación DOM del documento, como por ejemplo con LaTeX::TOM.

De los patrones que muestras, te falta por escapar '\', de la misma forma que en el resto del patrón.

En otro hilo, la solución que te di fue la de localizar la parte problemática, sacarla con la ayuda de pos() y de los array @+ y @-, transformar la parte con el cambio que queríamos, y luego insertarla de nuevo con la ayuda de substr().
JF^D Perl programming & Raku programming. Grupo en Telegram: https://t.me/Perl_ES
Avatar de Usuario
explorer
Administrador
Administrador
 
Mensajes: 14476
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España

Re: Expresión regular para texto anidado

Notapor pablgonz » 2014-12-21 22:34 @982

Entre más analizo el problema más detalles van saliendo. En fin, Perl es súper rápido para abrir y cerrar archivos así que crearé un par de archivos temporales en el camino y usando un hash cambiaré las palabras que me están dando problemas.

No es la solución ideal, pero funciona, ya que no pude dar con la expresión regular para ignorar lo que estaba dentro de \begin{postscript} ... \end{postscript} :cry:

Agradecido y deseando unas felices fiestas.
Pablo
pablgonz
Perlero nuevo
Perlero nuevo
 
Mensajes: 236
Registrado: 2010-09-08 21:03 @919
Ubicación: Concepción (Chile)

Re: Expresión regular para texto anidado

Notapor pablgonz » 2014-12-31 00:58 @081

Estoy casi listo con el script, pero, algo no anda bien. Va así:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. #!/usr/bin/perl
  2. use v5.18;
  3. use re 'eval';
  4. use autodie;                    # muere si ocurre un error
  5. use File::Basename;             # separa el archivo de entrada
  6.  
  7. # Constantes
  8. my $tempDir = ".";              # temporary directory
  9. my $imageDir = "images";        # where to save the images
  10. my $ignore = "ignore";          # ignore verbatim environment
  11. my $exacount = 1;               # Counter for images
  12. my $other = "other";            # otro entorno
  13. #--------------------- Arreglo de la extensión -------------------------
  14. my @SuffixList = ('.tex', '', '.ltx');               # posible extensión
  15. my ($name, $path, $ext) = fileparse($ARGV[0], @SuffixList);
  16. $ext = '.tex' if not $ext;
  17.  
  18. #---------------- Creamos el directorio para las imágenes --------------
  19. -e $imageDir or mkdir($imageDir,0744) or die "No puedo crear $imageDir: $!\n";
  20.  
  21. # Constantes
  22. my $BP = '\\\\begin{postscript}';
  23. my $EP = '\\\\end{postscript}';
  24. my $BPL = '\begin{postscript}';
  25. my $EPL = '\end{postscript}';
  26. my $sipgf = 'pgfpicture';
  27. my $nopgf = 'pgfinterruptpicture';
  28. my $graphics = "graphic=\{\[scale=1\]$imageDir/$name-fig";
  29.  
  30. ############################# PARTE 1 ##################################
  31. #--------------------------- Coment Verbatim ---------------------------
  32. #---------------- Creamos un hash con los cambios ----------------------
  33. my %cambios = (
  34. # pspicture    
  35.     '\pspicture'                => '\TRICKS',
  36.     '\endpspicture'             => '\ENDTRICKS',
  37. # pspicture
  38.     '\begin{pspicture'          => '\begin{TRICKS',
  39.     '\end{pspicture'            => '\end{TRICKS',
  40. # postscript
  41.     '\begin{postscript}'        => '\begin{POSTRICKS}',
  42.     '\end{postscript}'          => '\end{POSTRICKS}',
  43. # $other    
  44.     "\\begin\{$other"           => '\begin{OTHER',
  45.     "\\end\{$other"             => '\end{OTHER',
  46. # document
  47.     '\begin{document}'          => '\begin{DOCTRICKS}',
  48.     '\end{document}'            => '\end{DOCTRICKS}',
  49. # tikzpicture
  50.     '\begin{tikzpicture}'       => '\begin{TIKZPICTURE}',
  51.     '\end{tikzpicture}'         => '\end{TIKZPICTURE}',
  52. # pgfinterruptpicture
  53.     '\begin{pgfinterruptpicture'=> '\begin{PGFINTERRUPTPICTURE',
  54.     '\end{pgfinterruptpicture'  => '\end{PGFINTERRUPTPICTURE',
  55. # pgfpicture
  56.     '\begin{pgfpicture}'        => '\begin{PGFPICTURE}',
  57.     '\end{pgfpicture}'          => '\end{PGFPICTURE}',
  58. # ganttchart
  59.     '\begin{ganttchart}'        => '\begin{GANTTCHART}',
  60.     '\end{ganttchart}'          => '\end{GANTTCHART}',
  61. # circuitikz
  62.     '\begin{circuitikz}'        => '\begin{CIRCUITIKZ}',
  63.     '\end{circuitikz}'          => '\end{CIRCUITIKZ}',
  64. # forest    
  65.     '\begin{forest}'            => '\begin{FOREST}',
  66.     '\end{forest}'              => '\end{FOREST}',
  67. # tikzcd
  68.     '\begin{tikzcd}'            => '\begin{TIKZCD}',
  69.     '\end{tikzcd}'              => '\end{TIKZCD}',
  70. # dependency
  71.     '\begin{dependency}'        => '\begin{DEPENDENCY}',
  72.     '\end{dependency}'          => '\end{DEPENDENCY}',
  73. );
  74.  
  75. #--------------------- Coment Verbatim environment ---------------------
  76.  
  77. my @lineas;
  78. {
  79.    open my $FILE,'<',"$name$ext";
  80.    @lineas = <$FILE>;
  81.    close $FILE;
  82. }
  83.  
  84. #------------------------ Verbatim environments ------------------------
  85. my $ENTORNO  = qr/(?: (v|V)erbatim\*?| PSTexample | LTXexample| $ignore\*? | PSTcode | tcblisting\*? | spverbatim | minted | lstlisting | alltt | comment\*? | xcomment)/xi;
  86. #    
  87. my $DEL;
  88.  
  89. my $tcbverb = qr/\\(?:tcboxverb|myverb)/;
  90.  
  91. my $arg_brac = qr/(?:\[.+?\])?/;
  92.  
  93. my $arg_curl = qr/\{(.+)\}/;          
  94.  
  95. for (@lineas) {
  96.     if (/^\\begin\{($ENTORNO)(?{ $DEL = "\Q$^N" })\}/ .. /^\\end\{$DEL\}/) {
  97.         while (my($busco, $cambio) = each %cambios) {
  98.             s/\Q$busco\E/$cambio/g;
  99.         }
  100.     } # coment tcolorbox inline
  101.     elsif (m/$tcbverb$arg_brac$arg_curl/) {
  102.         while (my($busco, $cambio) = each %cambios) {
  103.             s/\Q$busco\E/$cambio/g;
  104.         }
  105.     } # close elsif
  106.  }
  107.  
  108. # Write
  109.  
  110. open my $SALIDA, '>', "$tempDir/$name-tmp$ext";
  111. print   $SALIDA @lineas;
  112. close   $SALIDA;
  113.  
  114. #------------------------ Coment inline Verbatim -----------------------
  115.  
  116. open my $ENTRADA, '<', "$tempDir/$name-tmp$ext";
  117. my $archivo;
  118. {
  119.     local $/;
  120.     $archivo = <$ENTRADA>;
  121. }
  122. close $ENTRADA;
  123.  
  124. ## Variables y constantes
  125. my $no_del = "\0";
  126. my $del    = $no_del;
  127.  
  128. ## Reglas
  129. my $llaves      = qr/\{ .+? \}                                                                  /x;
  130. my $no_corchete = qr/(?:\[ .+? \])?                                                             /x;
  131. my $delimitador = qr/\{ (?<del>.+?) \}                                                          /x;
  132. my $verb        = qr/(spv|v|V)erb [*]?                                                          /ix;
  133. my $lst         = qr/lstinline (?!\*) $no_corchete                                              /ix;
  134. my $mint        = qr/mint      (?!\*) $no_corchete $llaves                                      /ix;
  135. my $marca       = qr/\\ (?:$verb | $lst | $mint ) (\S) .+? \g{-1}                               /x;
  136. my $comentario  = qr/^ \s* \%+ .+? $                                                            /mx;
  137. my $definedel   = qr/\\ (?:   DefineShortVerb | lstMakeShortInline  ) $no_corchete $delimitador /ix;
  138. my $indefinedel = qr/\\ (?: UndefineShortVerb | lstDeleteShortInline) $llaves                   /ix;
  139.  
  140. while ($archivo =~
  141.         /   $marca
  142.         |   $comentario
  143.         |   $definedel
  144.         |   $indefinedel
  145.         |   $del .+? $del                                                       # delimitado
  146.         /pgmx) {
  147.  
  148.         my($pos_inicial, $pos_final) = ($-[0], $+[0]);                          # posiciones
  149.         my $encontrado = ${^MATCH};                                             # lo encontrado
  150.  
  151.     if ($encontrado =~ /$definedel/){                                           # definimos delimitador
  152.                         $del = $+{del};
  153.                         $del = "\Q$+{del}" if substr($del,0,1) ne '\\';         # es necesario "escapar" el delimitador
  154.                 }
  155.     elsif($encontrado =~ /$indefinedel/) {                                      # indefinimos delimitador
  156.                  $del = $no_del;                                      
  157.         }
  158.     else {                                                                      # aquí se hacen los cambios
  159.         while (my($busco, $cambio) = each %cambios) {
  160.                        $encontrado =~ s/\Q$busco\E/$cambio/g;                   # es necesario escapar $busco
  161.                         }
  162.         substr $archivo, $pos_inicial, $pos_final-$pos_inicial, $encontrado;     # insertamos los nuevos cambios
  163.  
  164.         pos($archivo)= $pos_inicial + length $encontrado;                        # re posicionamos la siguiente búsqueda
  165.         }
  166. }
  167.  
  168. # Write
  169.  
  170. open my $SALIDA, '>', "$tempDir/$name-tmp$ext";
  171.    print   $SALIDA "$archivo";
  172. close $SALIDA;
  173.  
  174. ############################# PARTE 2 ##################################
  175. #-------------- Convert pspicture into begin{pspicture} ----------------
  176.  
  177. open my $ENTRADA, '<', "$tempDir/$name-tmp$ext";
  178. my $archivo;
  179. {
  180.     local $/;
  181.     $archivo = <$ENTRADA>;
  182. }
  183. close $ENTRADA;
  184.  
  185. ## Partición del documento
  186.  
  187. my($cabeza,$cuerpo,$final) = $archivo =~ m/\A (.+?) (^\\begin{document} .+)(^\\end{document}.*)\z/msx;
  188.  
  189. #---------- Convert PStricks into Postscript environments --------------
  190.  
  191. # \pspicture to \begin{pspicture}
  192. $cuerpo =~ s/\\pspicture(\*)?(.+?)\\endpspicture/\\begin{pspicture$1}$2\\end{pspicture$1}/gmsx;
  193.  
  194. # $other
  195. $cuerpo =~ s/(\\begin\{$other.*?\}(.+?)\\end\{$other.*?\})/$BPL\n$1\n$EPL/gmsx;
  196.  
  197. # pspicture to Postscript
  198. $cuerpo =~ s/
  199.     (
  200.         (?:\\psset\{[^\}]+\}.*?)?
  201.         (?:\\begin\{pspicture(\*)?\})
  202.                 .*?
  203.         (?:\\end\{pspicture(\*)?\})
  204.     )
  205.     /$BPL\n$1\n$EPL/gmsx;
  206.  
  207. #---------- Convert PGF/TikZ into Postscript environments --------------
  208.  
  209. # pgfpicture
  210. $cuerpo =~ s/
  211.     (
  212.         \\begin{$sipgf}
  213.             .*?
  214.             (
  215.                 \\begin{$nopgf}
  216.                 .+?
  217.                 \\end{$nopgf}
  218.                 .*?
  219.             )*?
  220.         \\end{$sipgf}
  221.     )
  222.     /$BPL\n$1\n$EPL/gmsx;
  223.  
  224. # tikz
  225. $cuerpo =~ s/
  226.     (
  227.         (?:\\tikzset(\{(?:\{.*?\}|[^\{])*\}).*?)? # si está lo guardo
  228.         (?:\\begin\{tikzpicture\})       # aquí comienza la búsqueda
  229.                       .*?                # guardo el contenido en $1
  230.         (?:\\end\{tikzpicture\})         # termina la búsqueda
  231.     )                                    # cierra $1
  232.         /$BPL\n$1\n$EPL/gmsx;
  233.  
  234. # forest
  235. $cuerpo =~ s/
  236.         (
  237.             (?:\\begin\{forest\}) # aquí comienza la búsqueda
  238.                     .*?           # guardo el contenido en $1
  239.             (?:\\end\{forest\})   # termina la búsqueda
  240.         ) # cierra $1
  241.         /$BPL\n$1\n$EPL/gmsx;
  242.  
  243. # tikzcd
  244. $cuerpo =~ s/
  245.         (
  246.             (?:\\begin\{tikzcd\}) # aquí comienza la búsqueda
  247.                     .*?           # guardo      el contenido en $1
  248.             (?:\\end\{tikzcd\})   # termina la búsqueda
  249.         ) # cierra $1
  250.         /$BPL\n$1\n$EPL/gmsx;
  251.  
  252. # tikz-dependency
  253. $cuerpo =~ s/
  254.         (                              
  255.             (?:\\begin\{dependency\}) # aquí comienza la búsqueda
  256.                     .*?               # guardo  el contenido en $1
  257.             (?:\\end\{dependency\})   # termina la búsqueda
  258.         ) # cierra $1
  259.         /$BPL\n$1\n$EPL/gmsx;
  260.  
  261. # circuitikz
  262. $cuerpo =~ s/
  263.     (
  264.         (?:\\begin\{circuitikz\})     # aquí comienza la búsqueda
  265.                 .*?                   # guardo el contenido en $1
  266.         (?:\\end\{circuitikz\})       # termina la búsqueda
  267.     )                                 # cierra $1
  268.     /$BPL\n$1\n$EPL/gmsx;
  269.  
  270. # pgfgantt
  271. $cuerpo =~ s/
  272.        (       
  273.         (?:\\begin\{ganttchart\}) # aquí comienza la búsqueda
  274.                 .*?               # guardo el contenido en $1
  275.         (?:\\end\{ganttchart\})   # termina la búsqueda
  276.        )                          # cierra $1
  277.        /$BPL\n$1\n$EPL/gmsx;
  278.  
  279. # Eliminar duplicados
  280. $cuerpo =~ s/
  281.  
  282.         $BP                     # marca que buscamos
  283.         .*?                     # seguido de lo que sea
  284.         (?(?=$EP)(*SKIP))       # PERO si encontramos una marca de final, terminamos
  285.         \K                      # vale, si encontramos lo anterior, nos olvidamos de ello
  286.         $BP\n                   # quitar
  287.         (.*?)                   # mantener
  288.         $EP\n                   # quitar
  289.  
  290.      /$1/gmsx;
  291.  
  292. # Write
  293.  
  294. open my $SALIDA, '>', "$tempDir/$name-tmp$ext";
  295.    print   $SALIDA "$cabeza$cuerpo$final";
  296. close $SALIDA;
  297.  
  298. $cabeza .= <<"EXTRA";
  299. \\newenvironment{postscript}{}{}
  300. \\pagestyle{empty}
  301. EXTRA
  302.  
  303. # Poner el atributo añadido a PostScript
  304. while ($cuerpo =~ /\\begin\{postscript\}/gsm) {
  305.  
  306.     my $corchetes = $1;
  307.     my($pos_inicial, $pos_final) = ($-[1], $+[1]);      # posición donde están los corchetes
  308.  
  309.     if (not $corchetes) {
  310.         $pos_inicial = $pos_final = $+[0];              # si no hay corchetes, nos ponemos al final de \begin
  311.     }
  312.     if (not $corchetes  or  $corchetes =~ /\[\s*\]/) {  # si no hay corchetes, o están vacíos,
  313.         $corchetes = "[$graphics-$exacount}]";          # ponemos los nuestros
  314.     }
  315.     substr($cuerpo, $pos_inicial, $pos_final - $pos_inicial) = $corchetes;    
  316.     pos($cuerpo) = $pos_inicial + length $corchetes;    # reposicionamos la búsqueda de la exp. reg.
  317. }
  318. continue {
  319.     $exacount++;
  320. }
  321.  
  322. #------------------- Extract source for image files --------------------
  323.  
  324. while ($cuerpo =~ /$BP\[.+?(?<img_src_name>$imageDir\/.+?-\d+)\}\](?<code>.+?)(?=^$EP)/gsm) {
  325.     open my $SALIDA, '>', "$+{'img_src_name'}$ext";
  326.     print $SALIDA <<"EOC";
  327. $cabeza\\begin{document}$+{'code'}\\end{document}
  328. EOC
  329. close $SALIDA;
  330. }
  331. __END__
Coloreado en 0.008 segundos, usando GeSHi 1.0.8.4
Lo que no me funciona de forma correcta son las líneas donde debería eliminar los duplicados:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. # Eliminar duplicados
  2. $cuerpo =~ s/
  3.  
  4.         $BP                     # marca que buscamos
  5.         .*?                     # seguido de lo que sea
  6.         (?(?=$EP)(*SKIP))       # PERO si encontramos una marca de final, terminamos
  7.         \K                      # vale, si encontramos lo anterior, nos olvidamos de ello
  8.         $BP\n                   # quitar
  9.         (.*?)                   # mantener
  10.         $EP\n                   # quitar
  11.  
  12.      /$1/gmsx;
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4
Al escribir la "PARTE 1 y 2" por separado funciona todo bien y no capto donde está el error, uso local para abrir y cerrar los archivos, es decir, el abrir y cerrar $name-tmp" entre una y otra parte del script no deberían verse afectadas, aun así no funciona.
Si el fichero de entrada es:
Sintáxis: [ Descargar ] [ Ocultar ]
Using latex Syntax Highlighting
  1. \documentclass{article}
  2. % Las líneas que están en
  3. % éste sector no deben modificarse
  4. \begin{document}
  5.  
  6. \begin{verbatim}
  7. \begin{postscript}
  8. \begin{tikzpicture}
  9. \begin{ganttchart}
  10. No tocar  
  11. \end{ganttchart}
  12. \end{tikzpicture}
  13. \end{postscript}
  14. \end{verbatim}
  15.  
  16. \verb|\begin{postscript} o \end{tikzpicture}| % cambia
  17.  
  18.  
  19. Anidado dentro de postscript
  20. \begin{postscript}
  21. \begin{tikzpicture}
  22. Esto debería quedar bien
  23. \end{tikzpicture}
  24. \end{postscript}
  25.  
  26. Anidado dentro de postscript
  27. \begin{postscript}
  28. \begin{tikzpicture}
  29. \begin{ganttchart}{1}{12}
  30. Esto debería quedar bien
  31. \end{ganttchart}
  32. \end{tikzpicture}
  33. \end{postscript}
  34.  
  35. \end{document}
  36.  
  37. % no tocar de aquí en adelante
  38.  
  39. tikz anidado dentro de postscript
  40. \begin{tikzpicture}
  41. TEXTO
  42. \end{tikzpicture}
  43.  
  44. \begin{ganttchart}{1}{12}
  45. TEXTO
  46. \end{ganttchart}
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4
debería quedar:
Sintáxis: [ Descargar ] [ Ocultar ]
Using latex Syntax Highlighting
  1. \documentclass{article}
  2. % Las líneas que están en
  3. % éste sector no deben modificarse
  4. \begin{document}
  5.  
  6. \begin{verbatim}
  7. \begin{POSTRICKS}
  8. \begin{TIKZPICTURE}
  9. \begin{GANTTCHART}
  10. No tocar  
  11. \end{GANTTCHART}
  12. \end{TIKZPICTURE}
  13. \end{POSTRICKS}
  14. \end{verbatim}
  15.  
  16. \verb|\begin{POSTRICKS} o \end{TIKZPICTURE}| % cambia
  17.  
  18.  
  19. Anidado dentro de postscript
  20. \begin{postscript}
  21. \begin{tikzpicture}
  22. Esto debería quedar bien
  23. \end{tikzpicture}
  24. \end{postscript}
  25.  
  26. Anidado dentro de postscript
  27. \begin{postscript}
  28. \begin{tikzpicture}
  29. \begin{ganttchart}{1}{12}
  30. Esto debería quedar bien
  31. \end{ganttchart}
  32. \end{tikzpicture}
  33. \end{postscript}
  34.  
  35. \end{document}
  36.  
  37. % no tocar de aquí en adelante
  38.  
  39. tikz anidado dentro de postscript
  40. \begin{tikzpicture}
  41. TEXTO
  42. \end{tikzpicture}
  43.  
  44. \begin{ganttchart}{1}{12}
  45. TEXTO
  46. \end{ganttchart}
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4
junto a dos archivos de nombres test-fig-1.tex y test-fig-2.tex dentro de la carpeta images, pero, dentro de la carpeta images crea archivos de la forma:
Sintáxis: [ Descargar ] [ Ocultar ]
Using latex Syntax Highlighting
  1. \documentclass{article}
  2. % Las líneas que están en
  3. % éste sector no deben modificarse
  4. \newenvironment{postscript}{}{}
  5. \pagestyle{empty}
  6. \begin{document}
  7. \begin{postscript}[graphic={[scale=1]images/test-fig-2}]
  8. \begin{tikzpicture}
  9. Esto debería quedar bien
  10. \end{tikzpicture}
  11. \end{document}
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4
donde lo correcto sería:
Sintáxis: [ Descargar ] [ Ocultar ]
Using latex Syntax Highlighting
  1. \documentclass{article}
  2. % Las líneas que están en
  3. % éste sector no deben modificarse
  4. \newenvironment{postscript}{}{}
  5. \pagestyle{empty}
  6. \begin{document}
  7. \begin{tikzpicture}
  8. Esto debería quedar bien
  9. \end{tikzpicture}
  10. \end{document}
Coloreado en 0.000 segundos, usando GeSHi 1.0.8.4
es decir, la línea [graphic={[scale=1]images/test-fig-2}] no debería estar y la numeración de los ficheros debería ser correlativa.
Cualquier ayuda se agradece.
Feliz fin de año a todos en el foro.
Saludos.
Pablo
pablgonz
Perlero nuevo
Perlero nuevo
 
Mensajes: 236
Registrado: 2010-09-08 21:03 @919
Ubicación: Concepción (Chile)

AnteriorSiguiente

Volver a Básico

¿Quién está conectado?

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

cron