开发者

I want to create a perl code to extract what is in the parentheses and port it to a variable

开发者 https://www.devze.com 2023-03-05 10:15 出处:网络
I want to create a perl code to extract what is in the parentheses and port it to a vari开发者_运维百科able.

I want to create a perl code to extract what is in the parentheses and port it to a vari开发者_运维百科able. "(05-NW)HPLaserjet" should become "05-NW" Something like this:

  • Catch "("
  • take out any spaces that exsist in between ()
  • everything in between () = variable 1

How would I go about doing this?


This is a job for regular expressions. Looks confusing because parens are used as meta characters in regular expression and are also part of the pattern in your example, escaped by backslashes.

C:\temp $ echo (05-NW)HPLaserjet | perl -nlwe "print for m/\(([^)]+)\)/g"

Match opening paren, start capture group, match one or more characters that aren't the closing paren, close capture group, match closing paren.


You can use regular expressions (see perlretut) to match and capture the value. By assigning to a list, you can put your captures into named variables. The global variables $1, $2 etc. are also used for capture groups, so you can use that instead of list assignment if you like.

use strict;
use warnings;

while (<>) # read every line
{
  my ($printer_code) = m/
    \(              # Match literal opening parenthesis
      ([^\)]*)      # Capture group (printer_code): Match characters which aren't right parenthesis, zero or more times
    \)/x;           # Match literal closing parenthesis
    # The 'x' modifier allows you to add whitespace and comments to regex for clarity.
    # If you use it, make sure you use '\ ' (or '\s', etc.) for actual literal whitespace matching!
}

__DATA__
(05-NW)HPLaserjet


perldoc perlre

use warnings;
use strict; 

my $s = '(05-NW)HPLaserjet';
my ($v) = $s =~ /\((.*)\)/; # Grab everything between parens (including other parens)
$v =~ s/\s//g; # Remove all whitespace
print "$v\n";

__END__

05-NW

See also: Perl Idioms Explained - @ary = $str =~ m/(stuff)/g

0

精彩评论

暂无评论...
验证码 换一张
取 消