• Publicidad

Mostrar valor de celdas

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

Mostrar valor de celdas

Notapor BigBear » 2012-04-24 12:35 @566

Hola, estaba practicando el manejo de tablas mediante Tk y llegué a un punto en el que no sé cómo
mostrar el valor entero.

El problema está en la función show_cells(), la cual muestra solo los números. Mi idea es que muestre el valor completo. Lo he intentado mostrando con $_ pero no se muestra.

Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. #!/usr/bin/perl
  2. use warnings;
  3. use Tk;
  4. use Tk::Table;
  5. my $cols = 10;
  6. my $rows = 20;
  7. my %slct;
  8.  
  9. # ------------------------------------------------------------------------
  10.  
  11. sub show_cells {
  12.         print "Selected Cells: ";
  13.         foreach ( sort {$a <=> $b} (keys %slct)) {
  14.         #################################################Aca esta la duda
  15.         printf "%d,%d ",split (/\./,$_);
  16.  
  17.         }
  18.         print "\n";
  19. }
  20.  
  21. # ------------------------------------------------------------------------
  22.  
  23. sub toggle_slct {
  24.         my ($w, $t) = @_;
  25.         my ($row, $col) = $t->Posn( $w );
  26.         my $k = sprintf "%d.%02d",$row,$col;
  27.         if ($slct{$k}) {
  28.                 $w->configure(-background => 'white');
  29.                 print "Row: $row Col: $col unselected\n";
  30.                 delete($slct{$k});
  31.         } else {
  32.                 $w->configure(-background => 'grey');
  33.                 print "Row: $row Col: $col selected\n";
  34.                 $slct{$k} = 1;
  35.         }
  36. }
  37.  
  38. # ------------------------------------------------------------------------
  39.  
  40. #
  41. # create the main window and frame
  42. #
  43. my $mw = new MainWindow();
  44. my $tableFrame = $mw->Frame(-borderwidth => 2,
  45.                             -relief => 'raised')->pack;
  46. #
  47. # allocate a table to the frame
  48. #
  49. my $table = $tableFrame->Table(-columns => 8,
  50.                                -rows => 10,
  51.                                -fixedrows => 1,
  52.                                -scrollbars => 'se',
  53.                                -relief => 'raised');
  54. #
  55. # column headings
  56. #
  57. foreach my $c ( 1 .. $cols) {
  58.         my $hdr = "Row " . $c;
  59.         my $tmp = $table->Label(-text => $hdr,
  60.                                 -width => 6,
  61.                                 -relief => 'raised');
  62.         $table->put( 0, $c, $tmp );
  63. }
  64. #
  65. # populate the cells and bind an action to each one
  66. #
  67. foreach my $r ( 1 .. $rows ) {
  68.         foreach my $c ( 1 .. $cols ) {
  69.                 my $data = $r . "," . $c;
  70.                 my $tmp = $table->Label(-text => "hola".$data, -padx => 2,
  71.                                         -anchor => 'w',
  72.                                         -background => 'white',
  73.                                         -relief => 'groove');
  74.                 $tmp->bind('<Double-1>', [ \&toggle_slct, $table ]);
  75.                 $table->put( $r, $c, $tmp );
  76.         }
  77. }
  78. $table->pack( -expand => 'yes', -fill => 'both');
  79. #
  80. # create the menu bar, and add the "show" and "exit" buttons
  81. #
  82. my $buttonBar = $mw->Frame( -borderwidth => 4 )->pack(-fill => 'y');
  83. my $showB = $buttonBar->Button(-text => "Show",
  84.                                 -command => \&show_cells);
  85. my $exitB = $buttonBar->Button( -text => "Exit",
  86.                                 -width => 10,
  87.                                 -command => sub { exit });
  88. foreach ( $showB, $exitB ) {
  89.         $_->pack(-side => 'left', -padx => 2 );
  90. }
  91. #
  92. # start it up
  93. #
  94. MainLoop();
Coloreado en 0.007 segundos, usando GeSHi 1.0.8.4


¿ Alguien me puede ayudar ?
BigBear
Perlero frecuente
Perlero frecuente
 
Mensajes: 981
Registrado: 2009-03-01 18:39 @818

Publicidad

Re: Mostrar valor de celdas

Notapor explorer » 2012-04-24 18:50 @826

printf() saca el resultado en pantalla, ¿correcto?

Bueno, lo que vemos es que quieres cambiar el punto decimal anglosajón por la coma decimal española.

Entonces, es mejor hacerlo así:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. sub show_cells {
  2.     print "Selected Cells: ";
  3.     foreach my $celda ( sort { $a <=> $b } ( keys %slct ) ) {
  4.         (my $con_coma = $celda) =~ s/[.]/,/;       # este paso es necesario porque no queremos
  5.                                                    # modificar las claves de %slct
  6.         printf "%s ", $con_coma;
  7.     }
  8.     print "\n";
  9. }
  10.  
Coloreado en 0.002 segundos, usando GeSHi 1.0.8.4

Bueno, esto no deja de ser una chapuza... Lo ideal es usar las facilidades de configuración regional (las "locales"), para que los números salgan directamente como queremos:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. #!/usr/bin/perl
  2. use v5.12.4;
  3. use strict;
  4. use warnings;
  5. use diagnostics;
  6.  
  7. use locale;                            # Suponemos que están bien puestas en el sistema
  8. use POSIX qw(locale_h);                # Importamos setlocale() y definiciones
  9.  
  10. my $old = setlocale(LC_NUMERIC, "");   # Le damos un susto a LC_NUMERIC, para que tome
  11.                                        # la configuración regional local
  12.  
  13. say 3.14;                              # 3,14
  14.  
Coloreado en 0.002 segundos, usando GeSHi 1.0.8.4
JF^D Perl programming & Raku programming. Grupo en Telegram: https://t.me/Perl_ES
Avatar de Usuario
explorer
Administrador
Administrador
 
Mensajes: 14480
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España

Re: Mostrar valor de celdas

Notapor BigBear » 2012-04-24 20:02 @876

Me parece que me expresé mal porque lo que quería era mostrar el valor completo refiriéndome a "hola1,1". Eso era lo que quería sacar, porque acabo de probar el código que me sugeriste y sigo en lo mismo.
BigBear
Perlero frecuente
Perlero frecuente
 
Mensajes: 981
Registrado: 2009-03-01 18:39 @818

Re: Mostrar valor de celdas

Notapor explorer » 2012-04-25 07:37 @359

Si las celdas contiene lo que toggle_slct indica, sí que debería de funcionar:
Sintáxis: [ Descargar ] [ Ocultar ]
Using bash Syntax Highlighting
  1. > perl -E '$k = sprintf "%d.%02d",3,14; say $k; printf "%d,%d\n", split /[.]/, $k'
  2. 3.14
  3. 3,14
  4.  
Coloreado en 0.004 segundos, usando GeSHi 1.0.8.4

Si no funciona, quizás es que no has llamado en un primer momento a toggle_slct.

Para estar seguros, lo que puedes hacer en show_cells() es insertar estas líneas:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. use Data::Dumper;
  2. print Dumper \%slct;
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4
y así ves si lo que contiene ese hash es correcto.

Y el ejemplo que pones, de "hola1,1", no sirve, porque con "%d.%d" estás indicando que quieres sacar dos valores enteros, no una cadena ("hola1") y un número entero. Si el primer valor es una cadena, debes cambiar el primer"%d" por "%s".
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: Mostrar valor de celdas

Notapor BigBear » 2012-04-26 09:59 @457

Sí, ya había visto el hash con Data::Dumper, pero solo había números.

Igual ya lo solucioné todo con este código.

Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. #http://docstore.mik.ua/orelly/perl3/tk/ch18_04.htm
  2.  
  3. use Tk;
  4. use Tk::HList;
  5.  
  6. my $mw = MainWindow->new();
  7. $mw->geometry("400x400+20+20");
  8.  
  9. #my $hlist = $mw->HList(-columns => 4, -header => 1)->pack(-expand => 0, -fill => 'both');
  10.  
  11. my $hlist
  12.     = $mw->Scrolled( HList, -columns => 4, -header => 1, -width => 100, -scrollbars => 'se' )->pack( -side => 'right' );
  13.  
  14. $hlist->headerCreate( 0, -text => "ID" );
  15. $hlist->headerCreate( 1, -text => "From" );
  16. $hlist->headerCreate( 2, -text => "Subject" );
  17. $hlist->headerCreate( 3, -text => "Date" );
  18.  
  19. $hlist->bind( "<Double-1>", [ \&yeah ] );
  20.  
  21. $mw->Button( -text => "probando", -command => \&dos )->pack();
  22. $mw->Button( -text => "clean",    -command => \&uno )->pack();
  23.  
  24. MainLoop;
  25.  
  26. sub dos {
  27.     for ( reverse 1 .. 20 ) {
  28.         $hlist->add( $_, -text => "hola" . $_ );
  29.         $hlist->itemCreate( $_, 0, -text => $_ );
  30.         $hlist->itemCreate( $_, 1, -text => "probando2" );
  31.         $hlist->itemCreate( $_, 2, -text => "blaaaaaaaaaaaaaa3" );
  32.         $hlist->itemCreate( $_, 3, -text => "probando4" );
  33.     }
  34. }
  35.  
  36. sub uno {
  37.     $hlist->delete( 'all', 0 );
  38. }
  39.  
  40. sub yeah {
  41.     my @ar = $hlist->selectionGet();
  42.     print "[+] Marcaste : $ar[0]" . "\n";
  43.  
  44. }
  45.  
Coloreado en 0.003 segundos, usando GeSHi 1.0.8.4
Última edición por explorer el 2012-04-26 12:43 @571, editado 3 veces en total
Razón: Formateado de código con Perltidy
BigBear
Perlero frecuente
Perlero frecuente
 
Mensajes: 981
Registrado: 2009-03-01 18:39 @818


Volver a Básico

¿Quién está conectado?

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

cron