15.03.2020 Views

perl-language-es

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

open my $fh, '<', $filename or die "Failed to open file: $filename";

# You can then either read the file one line at a time...

while(chomp(my $line = <$fh>)) {

print $line . "\n";

}

# ...or read whole file into an array in one go

chomp(my @fileArray = <$fh>);

Si sabe que su archivo de entrada es UTF-8, puede especificar la codificación:

open my $fh, '<:encoding(utf8)', $filename or die "Failed to open file: $filename";

Después de terminar de leer el archivo, se debe cerrar el identificador de archivo:

close $fh or warn "close failed: $!";

Ver también: Leer un archivo en una variable.

Otra forma más rápida de leer un archivo es usar File :: Slurper Module. Esto es útil si trabajas

con muchos archivos.

use File::Slurper;

my $file = read_text("path/to/file"); # utf8 without CRLF transforms by default

print $file; #Contains the file body

Ver también: [Leyendo un archivo con sorbete]

Escribir en un archivo

Este código abre un archivo para escribir. Devuelve un error si no se pudo abrir el archivo.

También cierra el archivo al final.

#!/usr/bin/perl

use strict;

use warnings;

use open qw( :encoding(UTF-8) :std ); # Make UTF-8 default encoding

# Open "output.txt" for writing (">") and from now on, refer to it as the variable $fh.

open(my $fh, ">", "output.txt")

# In case the action failed, print error message and quit.

or die "Can't open > output.txt: $!";

Ahora tenemos un archivo abierto listo para la escritura que se accede a través de $fh (esta

variable se denomina gestor de archivo). A continuación podemos dirigir la salida a ese archivo

usando el operador de print :

# Print "Hello" to $fh ("output.txt").

print $fh "Hello";

# Don't forget to close the file once we're done!

close $fh or warn "Close failed: $!";

https://riptutorial.com/es/home 14

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!