perl - help removing unwanted characters within split
I've got a simple perl script that I need help tweaking. I was using split to separate the key and value. I almost got what I want but I want to remove the surrounding parentheses found in the input file. Also, could is there a way to sort (make it a开发者_JS百科n option) on the number values? Thanks for your help.
Ex. Input file
(hlu,1)
(kcq,4)
(ob2,1)
Perl script:
#!/usr/bin/perl
my $str = '';
open FILE;
while (<>) {
chomp;
my ($k, $v) = split /,/;
$str .= "$k:$v\n"
}
close FILE;
print "$str";
Results:
(hlu:1)
(kcq:4)
(ob2:1)
Want to see:
hlu:1
ob2:1
kcq:4
This is almost identical to Ivan's answer, except I used a single m//
instead of split()
-- reads simpler IMO
Also, not sure why you have open FILE
/ close FILE
if you're using while(<>)
... I got rid of 'em.
#!/usr/bin/perl
my @items = ();
# read input from stdin/@ARGV
while (<>) {
chomp;
m/\((.*),(.*)\)/;
push @items, [$1, $2];
}
# sort
@items = sort { $a->[1] <=> $b->[1] } @items;
foreach(@items)
{
my ($k, $v) = @$_;
print "$k:$v\n";
}
Change your loop to:
while (my $line = <FILE>) {
chomp $line;
$line =~ s/[()]//g;
my ($k, $v) = split /,/, $line;
$str .= "$k:$v\n"
}
You can remove all ()
symbols as mentioned by CanSpice. Or just remove starting/ending brackets:
$line =~ s/^\(|\)$//g; ## escaping () symbols with \
To sort your data you'll need to put it in array first, then sort array:
my @data_lines;
while (<>) {
chomp;
s/^\(|\)$//g;
push(@data_lines, [ split /,/ ]); ## save columns in array
}
## sort data numerically by second column
@data_lines = sort {$a->[1] <=> $b->[1]} @data_lines;
## output result
for my $row (@data_lines) {
my ($k, $v) = @$row; ## put values into variables for convenience
print "$k:$v\n";
}
Just for fun:
print "$_\n" for # 5
map join(':', @$_), # 4
sort { $a->[1] <=> $b->[1] } # 3
map [ /(\w+),(\d+)/ ], # 2
<> # 1
;
You can interpret such pipelines in reverse order:
- Read the input lines.
- Use a regex to capture the items we care about. Package those items (
$1
and$2
) in an array ref. - Sort those array refs numerically using element
[1]
. - Convert the little arrays to colon-separated strings.
- Print 'em.
精彩评论