1 / 25

Variables

Variables. Control de flujo. Ficheros. Grupo ejemplos. Acceso a Bases de Datos. Funciones específicas. Autenticación LDAP. Comunicación TCP/IP. Módulo Web.

roger
Télécharger la présentation

Variables

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Variables Control de flujo Ficheros Grupo ejemplos Acceso a Bases de Datos Funciones específicas Autenticación LDAP Comunicación TCP/IP Módulo Web Introducción al PERL Windows ActivePerl http://www.activestate.com/UNIX perl version 5.005_03http://www.perl.com/http://www.cpan.org/ports/win32 http://www.cpan.org/modules/index.htmlhttp://www.cpan.org/scripts/index.html Borja Pérez OñateArea de Sistemas - SICUZborja@unizar.es27.03.2003

  2. Variables normales:$v = “5“;$b = $v *3;print $b;>15$c = “$b es más que“ . $v; Print $c; >15 es mas que 5 Listas:@lista=(“5“, “luis“, “34hry“);print @lista[1];>luisOperaciones con listas: $elemento=pop(@lista) # saca el último push(@lista,$elemento) # añade al final $elemento=shift(@lista) # saca el primero unshift(@lista,$ele) # añade al principio @lista1=sort(@lista2) @lista3=reverse(@lista2) Operaciones con strings: Substr($string,despl,ncarac); lc($str) (minúsculas) uc($str) (mayúsculas) chop($string)

  3. Listas asociativas:%lista_asoc = (‘nom‘,‘Pedro‘,ap‘,Perez‘) ;$lista_asoc{‘telef‘} = “ 1234567“;print $lista_asoc{‘nom‘} >Pedro Manejo de listas asociativas @lista=keys %lista_asoc @lista=values %lista_asoc ($clave,$valor)=each(%lista_asoc) delete $lista_asoc{$clave}; Nombres variables de variables: $perico=“memoria“; $$perico=5; print $memoria; >5 @$nombre_de_lista; %$nombre_lista_asoc;

  4. For: For ($i=0;$i<100;$i++){ .... } While:while ($pepe < 7){ ... } If:if ($nombre eq “juan“){ ... } ==, <, > <>, <=, >=, ne, ... Foreach: Foreach $elemento (@lista){ ... } Foreach $clave (keys %lista_asoc){ ... } Foreach $clave_ord (sort keys %la){ ... }

  5. Abrir y cerrar: open (F,“nombre_fichero“); open (F,“>nombre_fichero“); close(F); Leer líneas del fichero:while ($linea = <F>){ ... } while (<F>){ ... } $linea = $_; @lineas = <F>; Escribir en fichero: print F “hola“; Entrada estandar:$resp=<STDIN>; chop($linea);

  6. Expresiones regulares Patrones en cadenas de caracteres. \d buscara un dígito \s espacio blanco o tabulador . Cualquier cosa Modificadores: • * 0 o más • + 1 o más • {n,m} >=n y <=m veces Buscar líneas que contengan: Mar 25 08:22:02 add login: /.*\d\d:\d\d:\d\d.*login/

  7. Correspondencia: m/lo_que_busca/; sobra la m si // if ($linea =~ /#/){ ... } if (!/^#/){ ... } usando $_ Sustitución: s/lo_que_busca/lo_que_pone/flags; Quitar blancos: $linea =~ s/\s{2,}//g; Cambiar una palabra por otra: s/perro/gato/g; actua sobre $_ Eliminar las mayúsculas $linea =~ s/[A-Z]//g;

  8. Split: Divide una cadena de caracteres usando un patrón. $frase=“hola,Juan“; ($uno,$dos)=split(/,/,$frase); $argumentos=“n=pp&a=jm&ci=0“; @campos=split(/&/,$argumentos); Foreach $un_campo(@campos) { ($clave,$valor)=split(/=/,$un_campo); print “$clave = $valor\n“; } While(<PASSWD>){ @datos=split(/:/); print @datos[1]; }

  9. Fecha y hora: ($sec,$min,$hora,$diames,$mes,$anno,$diasem,$diaanno,$verano) = localtime(time); El año desde 1900 (hay que sumar 1900) El mes entre 0 y 11 (hay que sumar 1) Dia semana 0-6 (domingo-lunes) Generar desde una fecha el tiempo del sistema: $tiempo=timelocal($sec,$min,$hora,$diames,$mes,$anno); Encontrar los días, horas, minutos y segundos entre dos fechas: ($s,$m,$h,$d)=(localtime($timenuevo-$timeviejo)[0..2,7];

  10. Utilidad cp (copy): #!/usr/local/bin/perl open (E,“ficheroE“); open (S,“>ficheroS“); while ($linea = <E>) { print S $linea; } close(E); close(S);

  11. Quitar los comentarios: #!/usr/local/bin/perl open (E,“ficheroE“); open (S,“>ficheroS“); while (<E>) { if (! /^#/ ){ print S $_; } close(E); close(S);

  12. Comandos del sistema: # du -ks /export/home/* 8 /export/home/AsigADD.txt 0 /export/home/altas 3 /export/home/bep 7334 /export/home/diferencias 0 /export/home/error_add 8 /export/home/g9 0 /export/home/prysma.err 3448 /export/home/prysma.lis >cs.pl >7334 #!/usr/local/bin/perl foreach (`du -ks /export/home/*`){ s/\s+/ /g; if(s/(\d+) .*diferencias/$1/){ print "$_\n"; } } ($k,$n)=split(/ /); if ($n =~ /diferencias/){print “$k\n“;}

  13. Contar palabras: #!/usr/bin/perl $fich="/export/home/prysma.lis"; open(F,$fich); while(<F>){ s/\s+/ /g; @pdl=split(/ /); foreach $up (@pdl){ $npal{$up}++; } } foreach $p (sort keys %npal){ print "$p sale $npal{$p} veces\n"; } s/[;|,|:]//g;

  14. Fichero de configuración: # # Caracteristicas del servidor LDAP PORT:386 servidorLDAP:linpps.unizar.es rootdc:dc=personal,dc=unizar,dc=es #!/usr/bin/perl open (CNF,”conf)|| die “Error al abrir conf\n"; while (<CNF>){ if (! /^#/){ chop; if (s/^PORT://){$PORT=$_;} if (s/^servidorLDAP://){$servLDAP=$_;} if (s/^rootdc://){$rootdc=$_;} } }

  15. Página web dinámica: print "Content-type: text/html\n\n"; open (F,”plantilla); while (<F>){ s/#CAMPO1#/$valor1/g; s/#CAMPO2#/$valor2/g; .... print $_; } close(F);

  16. Envío de mail: ...... &enviamail($mensaje); ....... exit; sub enviamail{ my @men=@_; my $to=“borja\@unizar.es”; open (MAIL,"| /bin/mail -s \"Resultado\“ $to"); print MAIL "@men\n"; close(MAIL); }

  17. Bases de Datos: Módulos sobre DB: $dbh = DBI->connect( "dbi:Oracle:$inst", $user, $pass, { AutoCommit => 0, RaiseError => 1, PrintError => 0 } ) or die $DBI::errstr;

  18. Bases de Datos: use DBI(); $dbh = DBI->connect( "DBI:mysql:database=webct;host=localhost", “usuario", “password", {'RaiseError' => 1} ); $sqlcomand="delete from conteos"; $sth = $dbh->prepare($sqlcomand); $sth->execute(); $sqlcomand="select count(distinct cod_alum) from parejas"; $sth = $dbh->prepare($sqlcomand); $sth->execute(); ($total_alumnos)= $sth->fetchrow_array;

  19. Bases de Datos: use DBI(); $dbh = DBI->connect( "DBI:mysql:database=webct;host=localhost", “usuario", “password", {'RaiseError' => 1} ); $sc="select distinct centro from conteos order by centro"; $sth = $dbh->prepare($sc); $sth->execute(); while (($codigo_centro)= $sth->fetchrow_array) { $sc="select centro titulacion from conteos where centro > 100"; $sth = $dbh->prepare($sc); $sth->execute(); while (($codigo_centro,$cod_titu)= $sth->fetchrow_array) {

  20. Autenticación LDAP: #!/usr/bin/perl use Net::LDAP; $base = "ou=accounts,dc=unizar,dc=es"; $username="borja"; $password=“fgdew34"; $ldap = new Net::LDAP ("linpps.unizar.es", port=> 389); $ldap->bind(); $mesg = $ldap->search( base => $base, filter => "(&(uid=$username))", attrs => "dn" ); $entry = $mesg->pop_entry(); $dn = $entry->dn(); $result=$ldap->bind(dn=> $dn,password=> $password); if ( $result->code){ print "no se ha autenticado\n"; exit; } print " OK\n";

  21. TCP/IP servidor (demonio): #!/usr/bin/perl use IO::Socket; $PORT=2000; $server = IO::Socket::INET->new( Proto => 'tcp', LocalPort => $PORT, Listen => SOMAXCONN, Reuse => 1); die “No puedo configurar el servidor" unless $server; while ($client = $server->accept()) { $client->autoflush(1); while ( <$client>) { if (/quit|exit/i) { last; } print “$_”; print $client $_; #modo eco } close $client; }

  22. TCP/IP cliente: #!/usr/bin/perl use IO::Socket; open (F,">$fichero"); $host = "www.sophos.com"; $EOL = "\015\012"; $BLANK = $EOL x 2; $remote = IO::Socket::INET->new( Proto => "tcp", PeerAddr => $host, PeerPort => "http(80)", ); unless ($remote) { die “no puedo conectar con $host" }; $remote->autoflush(1); print $remote "GET /downloads/ide/".$version."_ides.zip HTTP/1.0" . $BLANK; while ($respuesta=<$remote>) { print F $respuesta; } close (F); close $remote;

  23. Módulo Web: #!/usr/bin/perl use CGI; $query = new CGI;$anno=$query->param('anno');$direccion=$query->param('direccion'); @nombres = $query->param print "Content-type: text/html\n\n"; use CGI; $q = new CGI; print $q->header, $q->start_html('hello world'), $q->h1('hello world'), $q->end_html;

  24. NO a la GUERRA NO a la GUERRA NO a la GUERRA NO a la GUERRA NO a la GUERRA

  25. use Win32::OLE; $ex = Win32::OLE->new('Excel.Application', sub {$_[0]->Quit;}) or die "Oops, cannot start Excel"; } # get a new workbook $book = $ex->Workbooks->Add; # write to a particular cell $sheet = $book->Worksheets(1); $sheet->Cells(1,1)->{Value} = "foo"; # write a 2 rows by 3 columns range $sheet->Range("A8:C9")->{Value} = [[ undef, 'Xyzzy', 'Plugh' ], [ 42, 'Perl', 3.1415 ]]; # print "XyzzyPerl" $array = $sheet->Range("A8:C9")->{Value}; for (@$array) { for (@$_) { print defined($_) ? "$_|" : "<undef>|"; } print "\n"; ) # save and exit $book->SaveAs( 'test.xls' ); undef $book; undef $ex;

More Related