database - Sorting list of names in Perl -


i trying learn perl , quite new less week.

i want sort list of names(in case fruits) , give them id. script gives them id want sort them well.

current code:

use strict; use warnings;  %unique;  open(my $infile, $argv[0]) || die "could not open file '$argv[0]' $!"; open(my $outfile, ">$argv[1]") || die "could not find file '>$argv[1]' $!";  while (<$infile>) {         @fields = split;          $fruit  = $fields[0];         $quantity   = $fields[1];          @parts = split(/[_.]/, $fruit);         $counter = ++$unique{$parts[1]}{$parts[2]};          print $outfile join("\t", $fruit, $quantity, "$fruit.$counter"), "\n"; } 

input:

apple   3 apple   50 apple   1 orange  51 orange  21 

current output:

apple   3   apple.1 apple   50  apple.2 apple   1   apple.3 orange  51  orange.1 orange  21  orange.2 

wanted output:

apple   1   apple.1 apple   3   apple.2 apple   50  apple.3 orange  21  orange.1 orange  51  orange.2 

or

apple   3   apple.2 apple   50  apple.3 apple   1   apple.1 orange  51  orange.2 orange  21  orange.1 

thanks

update:

new input:

apple   3   1 apple   50  2 apple   1   3 orange  51  3 orange  21  5 

wanted output

apple   1   3   apple.1 apple   3   1   apple.2 apple   50  2   apple.3 orange  21  5   orange.1 orange  51  3   orange.2 

# read in data @data; while (<>) {    chomp;    push @data, [ split(/\t/, $_, -1) ]; }  # sort @data = sort {    $a->[0] cmp $b->[0]   # name       ||    $a->[1] <=> $b->[1]   # quantity } @data;  # generate ids , output data. %counts; $row (@data) {    $id = join('.', $row->[0], ++$counts{ $row->[0] });    push @$row, $id;    print(join("\t", @$row), "\n"); } 

Comments

Popular posts from this blog

sql - VB.NET Operand type clash: date is incompatible with int error -

SVG stroke-linecap doesn't work for circles in Firefox? -

python - TypeError: Scalar value for argument 'color' is not numeric in openCV -