Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

How do I read the contents of a file?

by vroom (Pope)
on Jan 08, 2000 at 08:44 UTC ( #1879=categorized question: print w/replies, xml ) Need Help??
Contributed by vroom on Jan 08, 2000 at 08:44 UTC
Q&A  > files

Answer: How do I read the contents of a file?
contributed by vroom

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;
Answer: How do I read the contents of a file?
contributed by Roger

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;
Answer: How do I read the contents of a file?
contributed by TGI

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
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.
Answer: How do I read the contents of a file?
contributed by nite_man

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:
Answer: How do I read the contents of a file?
contributed by Mago

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.

Please (register and) log in if you wish to add an answer

  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?

    What's my password?
    Create A New User
    and all is quiet...

    How do I use this? | Other CB clients
    Other Users?
    Others examining the Monastery: (5)
    As of 2017-03-26 03:48 GMT
    Find Nodes?
      Voting Booth?
      Should Pluto Get Its Planethood Back?

      Results (313 votes). Check out past polls.