pangxia75 发表于 2018-8-31 10:38:59

perl两个神奇的数组@-和@+

  # cat perl-grep4.pl
  #!/bin/perl
  # perl-grep4.pl
  my $pattern = shift @ARGV;
  my $regex = eval { qr/$pattern/ };
  die "Check your pattern! $@" if $@;
  while()
  {
  if(m/$regex/)
  {
  print "$_";
  print "\t\t\$&: ",
  substr( $_, $-[$i],$+[$i] - $-[$i] ),
  "\n";
  foreach my $i ( 1 .. $#- )
  {
  print "$#-\n";
  print "\t\t\$$i: ",
  substr( $_,$-[$i],$+[$i] - $-[$i] ),
  "\n";
  }
  }
  }
  # perldoc -t perl| perl perl-grep4.pl "\b(\S)(\S)\1\b"
  http://www.cpan.org/       the Comprehensive Perl Archive
  $&: www
  $1: w
  $2: w
  http://www.pm.org/         the Perl Mongers
  $&: www
  $1: w
  $2: w
  #
  @-和@+两个数组非常的神奇,两者保存的是matched内容的offset(偏移量)
  也就是说每个match内容的起始offset值放置在@-数组中,结束offset值放置在@+数组中
  说白了@-和@+两个数组保存的是一系列的值。
  @-数组的第一个元素是matche内容的起始offset,@+数组的第一个元素是match内容的结尾offset
  随后才是$1,$2...的offset值。

页: [1]
查看完整版本: perl两个神奇的数组@-和@+