[SP-pm] Deletar linha atual do arquivo

Nelson Ferraz nferraz em gmail.com
Terça Novembro 21 07:40:51 PST 2006


Rudolfo rosa wrote:
> Galera,
>   minha primeira duvida: Como deletar a linha atual de um arquivo ??
> Eu achei uma solucao, mas acredito que nao eh a melhor.

Além da solução já proposta, vale a pena conhecer o Tie::File.

Tie::File associates the lines of a file with elements of an array. If 
you read or change the array, that reads or changes the file in the 
corresponding way. It's safe, fast, and easy.

perlfaq5 contains the question:

     How do I change one line in a file/delete a line in a file/insert a 
line in the middle of a file/append to the beginning of a file?

Tie::File is the answer to this question.

     * To change one line in a file, do $line[$n] = $new;.
     * To delete a line from a file, use splice @line, $n, 1, or shift 
@line (to delete the first line) or pop @line (to delete the last line).
     * To insert a line in the middle of a file, use splice @line, $n, 
0, $new.
     * To append to the beginning of a file, use unshift @line, $new.

Tie::File also answers some other questions:

     * push @line, $new works and does what you expect: It appends a new 
line to the end of a file.
     * $#line = 3 works and does what you expect: It sets the size of 
the file to 4. (This is the same as what it would do to a regular 
array.) If the file was longer than 4 lines, the extra lines are 
removed. If the file was shorter than 4 lines, it is padded out with 
extra empty lines.
     * @line = ("I", "like", "pie") works and does what you expect: It 
throws away the entire contents of the file and replaces it with the 
three lines I, like, and pie.
     * for (@line) { s/PERL/Perl/g } works and does what you expect: It 
searches through the file and replaces every occurrence of PERL with Perl.

Changing a file is now as easy as changing an array.

http://perl.plover.com/TieFile/

http://perldoc.perl.org/Tie/File.html

-- 
Nelson Corrêa de Toledo Ferraz

Segula Technologies (www.segula.fr)
Free Software Foundation Associate Member #3203
Sociedade Perl do Brasil (www.perl.org.br)
Rede Livre de Compartilhamento de Cultura Digital


Mais detalhes sobre a lista de discussão SaoPaulo-pm