By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
437,661 Members | 1,330 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 437,661 IT Pros & Developers. It's quick & easy.

How to sort the data?

P: 89
Hi I have one row of data from a database as @data.

I need to sort the items available in $data[1], 2,3,4,5,6,7,8 positions

For example if the data are as below:

man, women, man, man, women, man, man, man in their respective position. Then I want my output to be as below:

134678: man
25: woman


How do I do this? I am not so familiar with perl hash as a beginner. It would be of great help if someone helps me out.
Thanks and Regards
Jul 15 '08 #1
Share this Question
Share on Google+
5 Replies


nithinpes
Expert 100+
P: 410
You have to create a hash from the array with each unique element as key. Then parse the array and concatenate the position value for each element matching the key, as follows:

Expand|Select|Wrap|Line Numbers
  1. @data=(man, women, man, man, women, man, man, man);
  2.  
  3. foreach(@data) {
  4.  $entry{$_}++; 
  5.  #hash with each unique data as key & number of occurence as its value
  6. }
  7.  
  8. foreach my $key (sort keys %entry) {
  9.  my $i=1;
  10.  my $str;
  11.   foreach(@data) {
  12.   $str.="$i" if(/$key/); #concatenate the position 
  13.   $i++;
  14. }
  15.  print "$str: $key\n";
  16. }
  17.  
Jul 15 '08 #2

KevinADC
Expert 2.5K+
P: 4,059
another way using a hash of arrays:

Expand|Select|Wrap|Line Numbers
  1. @data = qw(man women man man women man man man);
  2. my %hash;
  3. my $i;
  4. foreach my $thing (@data) {
  5.    push @{$hash{$thing}},$i++;
  6. }
  7. for (keys %hash) {
  8.    print "$_:", join(',',@{  $hash{$_} }), "\n"; 
Jul 15 '08 #3

P: 5
Hi Lilly,


Good Luck,

Write me for any help in C, C++, Perl, PHP and UNIX related stuff. I will answer you with in the time with free of cost.

Rammohan Alampally,
HP Technologies
Bangalore
Jul 16 '08 #4

P: 36
Hi Lilly,


Good Luck,

Write me for any help in C, C++, Perl, PHP and UNIX related stuff. I will answer you with in the time with free of cost.


Rammohan Alampally,
HP Technologies
Bangalore

Hi ramohna may a simple way, no to complicate life with hasesh
Expand|Select|Wrap|Line Numbers
  1. @data=('man', 'women', 'man', 'man',
  2.        'women', 'man', 'man', 'man');
  3. my $str;
  4. my $women;
  5. for ($i = 1;$i <=$#data+1;$i++)
  6. {
  7.   $str.= $i if $data[$i-1]=~ /man/;
  8.    $women.= $i if $data[$i-1]=~ /women/;
  9.  
  10. }
  11. print "$str:man\n";
  12. print "$women:women";
  13.  
Jul 16 '08 #5

P: 89
Thanks for the help.
Jul 16 '08 #6

Post your reply

Sign in to post your reply or Sign up for a free account.