简体   繁体   中英

Perl: Removing characters up to certain point.

I've tried searching through questions already asked, but can't seem to find anything. I'm sure its incredibly simple to do, but I am completely new to Perl.

What I am trying to do is remove characters in an string up to a certain point. For example, I have:

Parameter1 : 0xFFFF

and what I would like to do is remove the "Parameter1:" and be left with just the "0xFFFF". If anyone can help and give a simple explanation of the operators used, that'd be great.

Sounds like you need the substr function.

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

  my $string = 'Parameter1 : 0xFFFF';
  my $fragment =  substr $string, 12;
  print "  string: <$string>\n";
  print "fragment: <$fragment>\n";
s/.*:\s*//;

or

$s =~ s/.*:\s*//;

This deletes everything up to and including the first occurrence of : followed by zero or more whitespace characters. With $s =~ it's applied to $s ; without it, it's applied to $_ .

Have you considered using something like Config::Std ?

Here is how to parse a configuration file like that by hand:

#!/usr/bin/perl

use strict; use warnings;

my %params;

while ( my $line = <DATA> ) {
    if ($line =~ m{
            ^
            (?<param> Parameter[0-9]+)
            \s*? : \s*?
            (?<value> 0x[[:xdigit:]]+)
        }x ) {
        $params{ $+{param} } = $+{value};
    }
}

use YAML;
print Dump \%params;

__DATA__
Parameter1 : 0xFFFF
Parameter3 : 0xFAFF
Parameter4 : 0xCAFE

With Config::Std :

#!/usr/bin/perl

use strict; use warnings;
use Config::Std;

my $config = do { local $/; <DATA> };

read_config \$config, my %params;

use YAML;
print Dump \%params;

__DATA__
Parameter1 : 0xFFFF
Parameter3 : 0xFAFF
Parameter4 : 0xCAFE

Of course, in real life, you'd pass a file name to read_config instead of slurping it.

I like split for these parameter/value pairs.

my $str = "Parameter1 : 0xFFFF";
my ($param, $value) = split /\s*:\s*/, $str, 2;

Note the use of LIMIT in the split, which limits the split to two fields (in case of additional colons in the value).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM