LinuxQuestions.org
Share your knowledge at the LQ Wiki.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 12-10-2009, 06:24 PM   #1
ifeatu
Member
 
Registered: Sep 2008
Distribution: Fedora 9
Posts: 68

Rep: Reputation: 15
Perl basic opening of files


I want to open a file and perform some "stuff" to it line by line.

Can you help with syntax for opening the file and reading it line by line?

here is the code I have so far:


Code:
open(MYINPUTFILE, "<STDIN>"

$_ = @ARGV

# Do stuff
 
Old 12-10-2009, 06:38 PM   #2
ghostdog74
Senior Member
 
Registered: Aug 2006
Posts: 2,697
Blog Entries: 5

Rep: Reputation: 244Reputation: 244Reputation: 244
perldoc perlopentut
 
0 members found this post helpful.
Old 12-10-2009, 06:41 PM   #3
chrism01
LQ Guru
 
Registered: Aug 2004
Location: Sydney
Distribution: Rocky 9.2
Posts: 18,359

Rep: Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751
Very basic starting point

Code:
    # Open cfg file
    open( CONFIG_FILE, "<$cfg_file" ) or
            die "Can't open cfg file: $cfg_file: $!\n";

    # Process cfg file records
    while ( defined ( $cfg_rec = <CONFIG_FILE> ) )
    {
        # Remove unwanted chars
        chomp $cfg_rec;                 # newline

        # your code here
    }

    # Close cfg file
    close (CONFIG_FILE) or
            die "Can't close cfg file: $cfg_file: $!\n";
http://perldoc.perl.org/
http://www.perlmonks.org/?node=Tutorials
 
1 members found this post helpful.
Old 12-10-2009, 06:42 PM   #4
kbp
Senior Member
 
Registered: Aug 2009
Posts: 3,790

Rep: Reputation: 653Reputation: 653Reputation: 653Reputation: 653Reputation: 653Reputation: 653
Try:

Code:
my $file = "test.txt";

open(FILEHANDLE, "$file") || die "Could not open $file";

while (<FILEHANDLE>) {

# do stuff

}

close(FILEHANDLE);
<edit>oops... too slow</edit>

cheers

Last edited by kbp; 12-10-2009 at 06:44 PM.
 
Old 12-10-2009, 06:54 PM   #5
ghostdog74
Senior Member
 
Registered: Aug 2006
Posts: 2,697
Blog Entries: 5

Rep: Reputation: 244Reputation: 244Reputation: 244
Quote:
Originally Posted by chrism01 View Post
Very basic starting point

Code:
    # Process cfg file records
    while ( defined ( $cfg_rec = <CONFIG_FILE> ) )
    {
        # Remove unwanted chars
        chomp $cfg_rec;                 # newline

        # your code here
    }
"defined" is not necessary.
 
0 members found this post helpful.
Old 12-10-2009, 07:15 PM   #6
chrism01
LQ Guru
 
Registered: Aug 2004
Location: Sydney
Distribution: Rocky 9.2
Posts: 18,359

Rep: Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751
Perl Cookbook Chap 8
Quote:
The <FH> operator returns undef on error or when end of the file is reached, so use it in loops like this:

while (defined ($line = <DATAFILE>)) {
chomp $line;
$size = length $line;
print "$size\n"; # output size of line
}
 
1 members found this post helpful.
Old 12-10-2009, 07:23 PM   #7
ghostdog74
Senior Member
 
Registered: Aug 2006
Posts: 2,697
Blog Entries: 5

Rep: Reputation: 244Reputation: 244Reputation: 244
Quote:
Originally Posted by chrism01 View Post
Perl Cookbook Chap 8

Perl Cookbook Chap 8 also says
Quote:
Because this is a common operation and that's a lot to type, Perl gives it a shorthand notation. This shorthand reads lines into $_ instead of $line. Many other string operations use $_ as a default value to operate on, so this is more useful than it may appear at first:

while (<DATAFILE>) {
chomp;
print length, "\n"; # output size of line
}
 
0 members found this post helpful.
Old 12-10-2009, 07:30 PM   #8
chrism01
LQ Guru
 
Registered: Aug 2004
Location: Sydney
Distribution: Rocky 9.2
Posts: 18,359

Rep: Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751Reputation: 2751
True, but I always use named vars, not $_. I often write substantial sized Perl progs, so I like to have all my vars explicit.
Possibly also due to having done about 9 yrs of C first...
 
1 members found this post helpful.
Old 12-10-2009, 07:48 PM   #9
Sergei Steshenko
Senior Member
 
Registered: May 2005
Posts: 4,481

Rep: Reputation: 454Reputation: 454Reputation: 454Reputation: 454Reputation: 454
Quote:
Originally Posted by ghostdog74 View Post
"defined" is not necessary.
It is necessary - you do not want a line consisting of single 0 to return FALSE.
 
Old 12-10-2009, 07:48 PM   #10
ghostdog74
Senior Member
 
Registered: Aug 2006
Posts: 2,697
Blog Entries: 5

Rep: Reputation: 244Reputation: 244Reputation: 244
Quote:
Originally Posted by chrism01 View Post
True, but I always use named vars, not $_. I often write substantial sized Perl progs, so I like to have all my vars explicit.
Possibly also due to having done about 9 yrs of C first...
Code:
while ( my $namedvar=<DATAFILE> ){
  ....
}
 
Old 12-10-2009, 07:50 PM   #11
ghostdog74
Senior Member
 
Registered: Aug 2006
Posts: 2,697
Blog Entries: 5

Rep: Reputation: 244Reputation: 244Reputation: 244
Quote:
Originally Posted by Sergei Steshenko View Post
It is necessary - you do not want a line consisting of single 0 to return FALSE.
how so? example?
 
Old 12-11-2009, 06:47 AM   #12
Telemachos
Member
 
Registered: May 2007
Distribution: Debian
Posts: 754

Rep: Reputation: 60
@Ifeatu: The modern norm is to use a three-argument form of open and lexically scoped filehandles (variables declared with my rather than barewords like FILE). You should also always check the return status of open (and close for that matter).

A simple example might look like this:
Code:
#!/usr/bin/env perl
use strict;
use warnings;

my $file = 'example.txt';

open my $file_handle, '<', $file
    or die "Can't open [$file] for reading: $!";

while (my $line = <$file_handle>) {
    print $line;
}

close $file_handle or die "Problem closing [$file]: $!";
You can use autodie to get rid of some of the boilerplate around open and close.
 
Old 12-12-2009, 11:19 AM   #13
makyo
Member
 
Registered: Aug 2006
Location: Saint Paul, MN, USA
Distribution: {Free,Open}BSD, CentOS, Debian, Fedora, Solaris, SuSE
Posts: 735

Rep: Reputation: 76
Hi.
Code:
#!/usr/bin/env bash

# @(#) s1	Demonstrate running perl script.

echo
set +o nounset
LC_ALL=C ; LANG=C ; export LC_ALL LANG
echo "Environment: LC_ALL = $LC_ALL, LANG = $LANG"
echo "(Versions displayed with local utility \"version\")"
version >/dev/null 2>&1 && version "=o" $(_eat $0 $1) perl
set -o nounset

echo
echo " perl code:"
cat p1

echo
echo " Data file data1:"
cat data1

echo
echo " Results:"
./p1

exit 0
producing:
Code:
% ./s1

Environment: LC_ALL = C, LANG = C
(Versions displayed with local utility "version")
OS, ker|rel, machine: Linux, 2.6.26-2-amd64, x86_64
Distribution        : Debian GNU/Linux 5.0 
GNU bash 3.2.39
perl 5.10.0

 perl code:
#!/usr/bin/perl

# @(#) p1	Demonstrate read, <>, without defined.

use warnings;
use strict;
use feature qw(switch say);
use 5.010;

my ($debug);
$debug = 0;
$debug = 1;

while ( my $line = <DATA> ) {
  print $line;
}

print "\n";
open( my $data, "<", "data1" ) or die " Cannot open file data1.\n";
while ( my $line = <$data> ) {
  print $line;
}

exit(0);

__DATA__

0
one
two
last

 Data file data1:

0
first
second
final

 Results:

0
one
two
last


0
first
second
final
Data includes empty line and "0".

At one time I had always used function defined in such situations. I don't know when the requirement changed (or apparently changed) ... cheers, makyo
 
Old 12-12-2009, 08:26 PM   #14
Telemachos
Member
 
Registered: May 2007
Distribution: Debian
Posts: 754

Rep: Reputation: 60
Quote:
Originally Posted by makyo View Post
Data includes empty line and "0".
Well, yes and no. Your DATA section includes lines consisting of "\n" and "0\n". Both of those, of course, come out true in a boolean context. I suppose that the fear is the edge case of a file with 0 and no newline character (which is unusual but can happen). Still, I can't say that it keeps me up nights.
 
Old 12-12-2009, 11:33 PM   #15
makyo
Member
 
Registered: Aug 2006
Location: Saint Paul, MN, USA
Distribution: {Free,Open}BSD, CentOS, Debian, Fedora, Solaris, SuSE
Posts: 735

Rep: Reputation: 76
Hi.
Quote:
Originally Posted by Telemachos View Post
... I suppose that the fear is the edge case of a file with 0 and no newline character (which is unusual but can happen). ...
Thanks; I agree about newline alone and "0" followed by newline. However, the Programming perl, 3rd, page 81, says:

Both of these while loops still implicitly test for whether the result of the assignment is defined ...

Adding then a "0" with no newline at the end of datafile data2, and running slightly modified versions of the previously posted codes now called s2 and p2:
Code:
#!/usr/bin/env bash

# @(#) s2	Demonstrate running perl script.

echo
set +o nounset
LC_ALL=C ; LANG=C ; export LC_ALL LANG
echo "Environment: LC_ALL = $LC_ALL, LANG = $LANG"
echo "(Versions displayed with local utility \"version\")"
version >/dev/null 2>&1 && version "=o" $(_eat $0 $1) perl
set -o nounset

echo
echo " perl code:"
cat p2

echo
echo " Data file data2:"
cat data2

echo
echo " Results:"
./p2

echo "That was the final line."
exit 0
produces:
Code:
% ./s2

Environment: LC_ALL = C, LANG = C
(Versions displayed with local utility "version")
OS, ker|rel, machine: Linux, 2.6.26-2-amd64, x86_64
Distribution        : Debian GNU/Linux 5.0 
GNU bash 3.2.39
perl 5.10.0

 perl code:
#!/usr/bin/perl

# @(#) p2	Demonstrate read, <>, without defined.

use warnings;
use strict;
use feature qw(switch say);
use 5.010;

my ($debug);
$debug = 0;
$debug = 1;

while ( my $line = <DATA> ) {
  print $line;
}

print "\n";
open( my $data, "<", "data2" ) or die " Cannot open file data1.\n";
while ( my $line = <$data> ) {
  print $line;
}

exit(0);

__DATA__

0
one
two
last

 Data file data2:

0
first
second
final
0
 Results:

0
one
two
last


0
first
second
final
0That was the final line.
So even the odd case seems to be handled without using the function defined explicitly ... cheers, makyo
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
The very basic Perl problem Gins Linux - General 2 05-01-2007 05:59 AM
perl files download instead of parsed on apache2 mod-perl2 not parsing perl files zeigerpuppy Debian 1 02-16-2006 05:31 AM
basic perl module trscookie Programming 10 11-21-2005 12:46 AM
problems opening perl files rhuser Linux - Software 2 02-18-2003 02:15 PM
problems opening perl files rhuser Linux - Software 3 02-18-2003 10:03 AM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 01:38 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration