简体   繁体   中英

Perl hash and array + sort

The code speaks for itself, didn't use sort in code because I unknown your use this is content code in perl.

/bash/perl
%ttys = ();
my @lsarray = `cat /home/delkav/labs-scripts/grep`;
my @array;
$array[0] = <STDIN>; < ONE
$array[1] = <STDIN>; < TWO
$array[2] = <STDIN>; < TRHEE
$array[3] = <STDIN>; < FOUR
$array[4] = <STDIN>; < FIVE
$array[5] = <STDIN>; < SIX
$array[6] = <STDIN>; < SEVEN
$array[7] = <STDIN>; < EIGHT
$array[8] = <STDIN>; < NINE
@ttys{@lsarray} = @array;
print "@{[%ttys]}\n"

content in /home/delkav/labs-scripts/grep is :

$90850
$0
$389
$469
$670
$750
$684
$21744
$604

the printing out the script

$684
SEVEN
$469
FOUR
$21744
EIGHT
$670
FIVE
$389
TRHEE
$90850
ONE
$0
TWO
$750
SIX
$604
NINE

I need the output how this.

$90850
ONE
$0
TWO
$389
THREE
$469
FOUR
$670
FIVE
$750
SIX
$684
SEVEN
$21744
EIGHT
$604
NINE

well, thanks for your help.

if you need to preserve the order, you shouldn't use a hash, because hash functions don't maintain the order. instead you should use an array ref. Maybe like this:

#!/bash/perl
my @ttys;
my @lsarray = map { chomp; $_ } `cat /home/delkav/labs-scripts/grep`;
my @array;
chomp($array[$_] = <>) for 0..8;
push @ttys, [$array[$_], $lsarray[$_]] for 0..$#array;
print "$_->[0]\n$_->[1]\n" foreach @ttys;

也许这样:

print "$_\n$ttys{$_}\n" for @lsarray;

You should always use strict and use warnings at the top of every program. You should also open the data file and read it in Perl rather than shelling out to cat .

This program does what you need.

use strict;
use warnings;

open my $fh, '<', '/home/delkav/labs-scripts/grep' or die $!;

my @numbers = qw/ ONE TWO THREE FOUR FIVE SIX SEVEN EIGHT NINE TEN /;

my $i = 0;
while (<$fh>) {
  print;
  print $numbers[$i++], "\n";
}

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