zoukankan      html  css  js  c++  java
  • [quote] How to read Perl command-line arguments.

    from 

    http://alvinalexander.com/perl/perl-command-line-arguments-read-args

    How to read Perl command-line arguments

    Perl FAQ: How do I read command-line arguments in Perl?

    Note: If you want to handle simple Perl command line arguments, such as filenames and strings, this tutorial shows how to do that. If you want to handle command-line options (flags) in your Perl scripts (like "-h" or "--help"), this new Perl getopts command line options/flags tutorial is what you need.

    Perl command line args and the @ARGV array

    With Perl, command-line arguments are stored in a special array named @ARGV. So you just need to read from that array to access your script's command-line arguments.

    ARGV array elements: In the ARGV array, $ARGV[0] contains the first argument, $ARGV[1] contains the second argument, etc. So if you're just looking for one command line argument you can test for $ARGV[0], and if you're looking for two you can also test for $ARGV[1], and so on.

    ARGV array size: The variable $#ARGV is the subscript of the last element of the @ARGV array, and because the array is zero-based, the number of arguments given on the command line is $#ARGV + 1.

    Example 1: A typical Perl command line args example

    A typical Perl script that uses command-line arguments will (a) test for the number of command line arguments the user supplied and then (b) attempt to use them. Here's a simple Perl script named name.pl that expects to see two command-line arguments, a person's first name and last name, and then prints them:

    #!/usr/bin/perl -w
    
    # (1) quit unless we have the correct number of command-line args
    $num_args = $#ARGV + 1;
    if ($num_args != 2) {
      print "
    Usage: name.pl first_name last_name
    ";
      exit;
    }
    
    # (2) we got two command line args, so assume they are the
    # first name and last name
    $first_name=$ARGV[0];
    $last_name=$ARGV[1];
    
    print "Hello, $first_name $last_name
    ";
    

    This is fairly straightforward, where adding 1 to $#ARGV strikes me as the only really unusual thing.

    To test this script on a Unix/Linux system, just create a file named name.pl, then issue this command to make the script executable:

    chmod +x name.pl
    

    Then run the script like this:

    ./name.pl Alvin Alexander
    

    Or, if you want to see the usage statement, run the script without any command line arguments, like this:

    ./name.pl
    
  • 相关阅读:
    Windows下搭建JSP开发环境
    ssh 学习笔记
    18 11 27 长连接 短链接
    18 11 26 用多进程 多线程 携程 实现 http 服务器的创建
    18 11 24 简单的http服务器
    关于 某个智慧树课堂的 机器与机器交流方法
    18 11 23 正则学习
    尝试解决 : Microsoft Visual C++ 14.0 is required 的问题
    18 11 20 网络通信 ----多任务---- 携程 ----生成器
    18 11 20 网络通信 ----多任务---- 携程 ----迭代器
  • 原文地址:https://www.cnblogs.com/lake-of-embedded-system/p/3508184.html
Copyright © 2011-2022 走看看