zoukankan      html  css  js  c++  java
  • Perl 学习手札之二: Guide to experienced programmers

    open a file and return its number of lines.

    Version 1st:

    #!/usr/bin/perl
    use strict;
    use warnings;

    my $filename = "linesfile.txt"; # the name of the file

    open(FH, $filename);    # open the file
    my @lines = <FH>;       # read the file
    close(FH);              # close the file

    my $count = scalar @lines;  # the number of lines in the file
    print("There are $count lines in $filename\n");

    Version 2nd

    #!/usr/bin/perl
    use strict;
    use warnings;
    use IO::File;

    my $filename = "linesfile.txt"; # the name of the file

    # open the file - with simple error reporting
    my $fh = IO::File->new( $filename, "r" );
    if(! $fh) {
        print("Cannot open $filename ($!)\n");
        exit;
    }

    # count the lines
    my $count = 0;
    while( $fh->getline ) {
        $count++;
    }

    # close and print
    $fh->close;
    print("There are $count lines in $filename\n");

    Version 3rd:

    #!/usr/bin/perl
    use strict;
    use warnings;
    use IO::File;

    main(@ARGV);

    # entry point
    sub main
    {
        my $filename = shift || "linesfile.txt";
        my $count = countlines( $filename );
        message("There are $count lines in $filename");
    }

    # countlines ( filename ) - count the lines in a file
    # returns the number of lines
    sub countlines
    {
        my $filename = shift;
        error("countlines: missing filename") unless $filename;

        # open the file
        my $fh = IO::File->new( $filename, "r" ) or
            error("Cannot open $filename ($!)\n");
        
        # count the lines
        my $count = 0;
        $count++ while( $fh->getline );

        # return the result
        return $count;    
    }

    # message ( string ) - display a message terminated with a newline
    sub message
    {
        my $m = shift or return;
        print("$m\n");
    }

    # error ( string ) - display an error message and exit
    sub error
    {
        my $e = shift || 'unkown error';
        print("$0: $e\n");
        exit 0;
    }

    note: 以上的三个script都是在做一个事情,统计一个文件的行数, 相比下第三个更具备扩展性,更易于维护。

     注意此时shift的用法;

    type "perldoc IO:FIle" in terminal

    type "perldoc -f" in terminal

    if using eclipse, right click and choose Perldoc, and will get the same as in terminal



  • 相关阅读:
    PHP远程下载图片,微信头像存到本地,本地图片转base64
    jQuery Validate自定义错误信息,自定义方法
    创建自己的composer包
    js,JQ获取短信验证码倒计时
    JQ JS复制到剪贴板
    js,JQuery 生成二维码
    js,JQuery实现,带筛选,搜索的select
    HTML5拖放牛刀小试
    HTML5上传图片预览功能
    一次dropzone体验
  • 原文地址:https://www.cnblogs.com/hanleilei/p/2271401.html
Copyright © 2011-2022 走看看