Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

How do I read the contents of a file?

by vroom (Pope)
on Jan 08, 2000 at 08:44 UTC ( #1879=perlquestion: print w/replies, xml ) Need Help??

vroom has asked for the wisdom of the Perl Monks concerning the following question: (files)

How do I read the contents of a file?

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How do I read the contents of a file?
by vroom (Pope) on Jan 11, 2000 at 00:22 UTC
    All you need to do is use open:
    open FILEHANDLE, filename;
    Then all you have to do is read from your FILEHANDLE with <FILEHANDLE>. If you assign this to a scalar like $line=<FILE>, you'll get one line. However if you set it equal to an array like @lines=<FILE> you'll get all the lines.

    Then you should use close when you're finished reading from the file:

    open FILE, "myfile" or die "Couldn't open: $!"; @lines=<FILE>; #get all the lines from the file close FILE;
    open FILE2, "myfile2" or die "Couldn't open: $!"; while(<FILE2>){ #reads in from the file a line at a time and puts it +in the default variable print $_; #print the default variable $_ which the line is stor +ed in. } close FILE2;
Re: How do I read the contents of a file?
by Roger (Parson) on Sep 12, 2003 at 04:48 UTC
    Seeing that no one is using IO::File to open files, I will state the alternative (preferred) method of file handling. I know this is an old question, I am just stating the obvious here, but this post is to offer guidance to the beginner, isn't it?

    To open a file with IO::File,
    use IO::File; $f = new IO::File "filename.txt", "r";
    To read data from the file, just use the <> operator:
    while (<$f>) { ... do something here... }
    To close the file afterwards, simply undefine $f:
    undef $f;
      If you're a fan of lexical scoping, it could be used to improve the previous example by removing the need to undef $f in order to close the handle. With lexical scoping, when $f falls out of scope, the file is closed implicitly. See the following example:

      use strict; use warnings; use IO::File; { my $f = new IO::File "filename.txt", "r"; while (<$f>) { # do your stuff } }

      As the outter pair of curly brackets closes, so does the block in which $f was defined, and thus $f falls from scope, and thus is undefined, and thus the file to which it refers is implicitly closed.

      Dave

      "If I had my life to do over again, I'd be a plumber." -- Albert Einstein

      Since this is a newbie tutorial, it may be worth explaining that the contents of the record read are available in the $_ variable, in the block "... do something here...".

      For example, if you wanted to PRINT the file, you would say:

      while (<$f>) { print $_; # $_ contains the record most recently read # The "$_" is implied if omitted, so you could simply # say: print; # # If you need to append a newline after each record, # use : print "$_\n"; }
      Seeing that no one is using IO::File to open files, I will state the alternative (preferred) method of file handling.
      I've seen this designation "preferred" several times now. This isn't an attack, but a genuine question. What is the source for this? I see in perl5004delta that the IO:: family is preferred over the older FileHandle module, but nowhere do I see any reference to open() being no longer the preferred way to open files.
Re: How do I read the contents of a file?
by TGI (Parson) on Sep 08, 2000 at 03:41 UTC

    You can also change the record separator. The record separator is the character that perl uses to decide how much data to take in at once.

    It is accessed with the special variable $/ and the default value is \n.

    Some examples:

    $/ = "\n"; #default value $file=<DATA>; #gets one line @file=<DATA>; #gets all lines, each line in one value print "$file\n\n"; print join "|", @file; __DATA__ 1,2,3 4,5,6 7,8,9
    prints:
    1,2,3 4,5,6 |7,8,9
    While but if you set $/ = ","; you get:
    1, 2,|3 4,|5,|6 7,|8,|9
    Note that in the second example, "3\n4," is a record.
Re: How do I read the contents of a file?
by nite_man (Deacon) on Mar 07, 2003 at 12:56 UTC
    You can use the function read for reading of file content in the string variable:
    my $file_cont; # define a variable for keeping of file content my $fname = '/tmp/your_file'; open INPUT, $fname or die "Can't open file $fname: $!"; binmode INPUT; # If your file is binare read INPUT, $file_cont, -s $fname; close INPUT or die "Can't close file $fname: $!";
    Format of function  read is following:
    read FILEHANDLE,SCALAR,LENGTH,OFFSET or read FILEHANDLE,SCALAR,LENGTH
Re: How do I read the contents of a file?
by Mago (Parson) on Jul 08, 2003 at 15:02 UTC

    Para os membros ou futuros membros da lingua portuguesa.

    To the members or future members of the Portuguese language.

    Como é de normal encontramos em Perl diversas maneiras de fazer uma mesma rotina vou colocar de maneira bem simples, como construir uma função de leitura de uma arquivo, onde será retornado um array, onde cada posição representa um linha do arquivo.

    As it is common in Perl to find several ways to do the same thing, I will demonstrate a very simple way to construct a file reading function where an array is returned in which each element represents one line of the file.


    sub le { my $nomeArq = $_[0]; # recebe com parâmetro o nome do arquivo. my @arrayArq; my $linha; my $num = 0; open (ARQ, "< $nomeArq") or die "Erro ao abrir o arquivo: $nomeArq +: $!"; # Abre o arquivo ou mata o processo com uma mensagem de erro. while ($linha = <ARQ>) { # Varre todas as linhas do arquivo. $arrayArq[$num] = $linha; # Insere linha no array. $num++; } close ARQ; # Fecha o Arquivo return @arrayArq; }

    Gostaria de lembrar que essa é uma função bem simples para que um iniciante possa entender facilmente como ela funciona.

    I would like to point out that this is an example simple enough for a beginner to easily understand how it works.

    É natural que a mesma seja melhorada, para sua efetiva utilização.

    Naturally this can be adjusted to better fit a particular use.

    English translation by QandAEditors.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1879]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (3)
As of 2021-04-20 03:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?