Chinaunix首页 | 论坛 | 博客
  • 博客访问: 433057
  • 博文数量: 79
  • 博客积分: 8385
  • 博客等级: 中将
  • 技术积分: 3625
  • 用 户 组: 普通用户
  • 注册时间: 2005-09-26 14:42
文章分类

全部博文(79)

文章存档

2011年(10)

2010年(40)

2009年(21)

2008年(8)

分类:

2009-06-09 22:01:16


This how-to comes with no guaratees other than the fact that these code segments were copy/pasted from code that I wrote and ran successfully.

Solution

    sub read_file
    {
        my ( $f ) = @_;
        open F, "< $f" or die "Can't open $f : $!";
        my @f = ;
        close F;
        return wantarray ? @f : \@f;
    }

Solution

    sub write_file
    {
        my ( $f, @data ) = @_;
        @data = () unless @data;
        open F, "> $f" or die "Can't open $f : $!";
        print F @data;
        close F;
    }

Solution

    open( FILE, "< $filename" ) or die "Can't open $filename : $!";
    while(  ) {
        print;
    }
    close FILE;

Solution

    my $infile = 'foo.txt';
    my $outfile = 'bar.txt';
    open IN, "< $infile" or die "Can't open $infile : $!";
    open OUT, "> $outfile" or die "Can't open $outfile : $!";
    print OUT ;
    close IN;
    close OUT;

Read the file content using a while loop. For each line read, ignore the comments, and skip blank lines. Push all other lines of data into an array named lines. The chomp is done after the comment and blank line portion inorder to avoid unnecessary processing time.

Solution

    while(  ) {
        s/#.*//;            # ignore comments by erasing them
        next if /^(\s)*$/;  # skip blank lines
        chomp;              # remove trailing newline characters
        push @lines, $_;    # push the data line onto the array
    }

Example

    sub read_file
    {
        my( $filename ) = shift;
        my @lines;
        open( FILE, "< $filename" ) or die "Can't open $filename : $!";
        while(  ) {
            s/#.*//;            # ignore comments by erasing them
            next if /^(\s)*$/;  # skip blank lines
            chomp;              # remove trailing newline characters
            push @lines, $_;    # push the data line onto the array
        }
        close FILE;
        return \@lines;  # reference
    }


Alex BATKO


阅读(497) | 评论(1) | 转发(1) |
给主人留下些什么吧!~~

chinaunix网友2009-06-09 22:59:30

http://perldoc.perl.org/perlopentut.html