1

我刚刚开始使用 Perl,我非常喜欢它。我正在编写一些基本功能,但我真正想做的是使用控制台命令智能地使用这些功能。例如,假设我有一个添加两个数字的函数。我希望能够在控制台中输入“add 2, 4”并读取第一个单词,然后将这两个数字作为参数传递给“add”函数。本质上,我在使用 Perl ^^' 创建一些基本脚本时寻求帮助。

我对如何在 VB 中执行此操作有一些模糊的想法,但是 Perl,我不知道从哪里开始,也不知道哪些函数对我有用。是否有类似 VB.net 的“拆分”功能,您可以将标量的内容分解为数组?例如,有没有一种简单的方法可以一次分析一个标量中的一个单词,或者遍历一个标量直到遇到分隔符?

我希望你能帮助,任何建议表示赞赏!请记住,我不是专家,我几周前就开始使用 Perl,而我只做 VB.net 半年。

谢谢!

编辑:如果您不确定要建议什么并且您知道任何可能有帮助的简单/直观的资源,那也将不胜感激。

4

3 回答 3

3

制作一个按名称分派给命令的脚本相当容易。这是一个简单的例子:

#!/usr/bin/env perl

use strict;
use warnings;

# take the command name off the @ARGV stack
my $command_name = shift;

# get a reference to the subroutine by name
my $command = __PACKAGE__->can($command_name) || die "Unknown command: $command_name\n";

# execute the command, using the rest of @ARGV as arguments
# and print the return with a trailing newline
print $command->(@ARGV);
print "\n";

sub add {
  my ($x, $y) = @_;
  return $x + $y;
}

sub subtract {
  my ($x, $y) = @_;
  return $x - $y;
}

这个脚本(比如它的名字myscript.pl)可以被称为

$ ./myscript.pl add 2 3

或者

$ ./myscript.pl subtract 2 3

一旦你玩了一段时间,你可能想更进一步,为这种事情使用一个框架。有几个可用的,例如App::Cmd或者您可以采用上面显示的逻辑并按照您认为合适的方式进行模块化。

于 2013-03-12T21:41:35.547 回答
1

这是一个简单脚本语言的简短实现。

每条语句只有一行长,并具有以下结构:

Statement = [<Var> =] <Command> [<Arg> ...]
# This is a regular grammar, so we don't need a complicated parser.

令牌由空格分隔。一个命令可以接受任意数量的参数。这些可以是 variables $var、 string"foo"或数字(int 或 float)的内容。

由于这些是 Perl 标量,因此字符串和数字之间没有明显的区别。

这是脚本的序言:

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

strict并且warnings在学习 Perl 时必不可少,否则可能会出现太多奇怪的东西。这use 5.010是一个最低版本,它还定义了say内置函数(像 aprint但附加了一个换行符)。

现在我们声明两个全局变量:%env哈希(表或字典)将变量名与其值相关联。%functions保存我们的内置函数。这些值是匿名函数。

my %env;

my %functions = (
  add => sub { $_[0] + $_[1] },
  mul => sub { $_[0] * $_[1] },
  say => sub { say $_[0] },
  bye => sub { exit 0 },
);

现在是我们的读取评估循环(默认情况下我们不打印)。readline 运算符<>将从指定为第一个命令行参数的文件中读取,如果没有提供文件名,则从 STDIN 中读取。

while (<>) {
  next if /^\s*\#/; # jump comment lines
  # parse the line. We get a destination $var, a $command, and any number of @args
  my ($var, $command, @args) = parse($_);
  # Execute the anonymous sub specified by $command with the @args
  my $value = $functions{ $command }->(@args);
  # Store the return value if a destination $var was specified
  $env{ $var } = $value if defined $var;
}

那是相当微不足道的。现在来一些解析代码。Perl 使用运算符将​​正则表达式“绑定”到字符串=~。正则表达式可能看起来像/foo/m/foo/。这些/x标志允许我们在我们的正则表达式中包含与实际空格不匹配的空格。该/g标志在全球范围内匹配。这也启用了\G断言。这是最后一场成功的比赛结束的地方。该/c标志对于这种m//gc样式解析一次使用一个匹配项以及防止正则表达式引擎在输出字符串中的位置被重置很重要。

sub parse {
  my ($line) = @_; # get the $line, which is a argument
  my ($var, $command, @args); # declare variables to be filled

  # Test if this statement has a variable declaration
  if ($line =~ m/\G\s* \$(\w+) \s*=\s* /xgc) {
    $var = $1; # assign first capture if successful
  }

  # Parse the function of this statement.
  if ($line =~ m/\G\s* (\w+) \s*/xgc) {
    $command = $1;
    # Test if the specified function exists in our %functions
    if (not exists $functions{$command}) {
      die "The command $command is not known\n";
    }
  } else {
    die "Command required\n"; # Throw fatal exception on parse error.
  }

  # As long as our matches haven't consumed the whole string...
  while (pos($line) < length($line)) {
    # Try to match variables
    if ($line =~ m/\G \$(\w+) \s*/xgc) {
      die "The variable $1 does not exist\n" if not exists $env{$1};
      push @args, $env{$1};
    }
    # Try to match strings
    elsif ($line =~ m/\G "([^"]+)" \s*/xgc) {
      push @args, $1;
    }
    # Try to match ints or floats
    elsif ($line =~ m/\G (\d+ (?:\.\d+)? ) \s*/xgc) {
      push @args, 0+$1;
    }
    # Throw error if nothing matched
    else {
      die "Didn't understand that line\n";
    }
  }
  # return our -- now filled -- vars.
  return $var, $command, @args;
}

Perl 数组可以像链表一样处理:shift删除并返回第一个元素(pop对最后一个元素执行相同的操作)。push在末尾添加一个元素,添加unshift到开头。

Out little 编程语言可以执行简单的程序,例如:

#!my_little_language
$a = mul 2 20
$b = add 0 2
$answer = add $a $b
say $answer
bye

如果 (1) 我们的 perl 脚本保存在 中my_little_language,设置为可执行,并且在系统 PATH 中,并且 (2) 上面的文件以我们的小语言保存为meaning_of_life.mll,并且也设置为可执行,那么

$ ./meaning_of_life

应该能够运行它。

输出很明显42。请注意,我们的语言还没有字符串操作或对变量的简单赋值。此外,如果能够直接调用具有其他函数返回值的函数,那就太好了。这需要某种括号或优先机制。此外,该语言需要更好的批处理错误报告(它已经支持)。

于 2013-03-12T20:34:52.090 回答
1

您想解析命令行参数。Aspace作为分隔符,所以只需执行./add.pl 2 3以下操作:

$num1=$ARGV[0];
$num2=$ARGV[1];

print $num1 + $num2;

将打印5

于 2013-03-12T18:13:57.860 回答