Perl: Reading Files

In Perl, files can be read using handles as follows: Suppose, you want to read a following file called "program.txt" that contains following data using perl program:

1: perl 2: php 3: java 4: jsp

The program that would read this and print languages is:

#!/usr/bin/perl $fileName="program.txt"; open( fileHandle, $fileName); while(){ chop; # chop is used to remove \n ('end of line' from each line). my($id, $language) = split(':', $_); print "Language is $language \n"; }

The output of the above file is:

Language is perl Language is php Language is java Language is jsp

Post your Answer

  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <c>, <cpp>, <drupal5>, <drupal6>, <java>, <javascript>, <php>, <python>, <ruby>. Beside the tag style "<foo>" it is also possible to use "[foo]". PHP source code can also be enclosed in <?php ... ?> or <% ... %>.

More information about formatting options