How to sort the data? | Member | | Join Date: Jul 2008
Posts: 70
| | |
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
|  | Expert | | Join Date: Dec 2007
Posts: 400
| | | re: How to sort the data?
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: -
@data=(man, women, man, man, women, man, man, man);
-
-
foreach(@data) {
-
$entry{$_}++;
-
#hash with each unique data as key & number of occurence as its value
-
}
-
-
foreach my $key (sort keys %entry) {
-
my $i=1;
-
my $str;
-
foreach(@data) {
-
$str.="$i" if(/$key/); #concatenate the position
-
$i++;
-
}
-
print "$str: $key\n";
-
}
-
|  | Expert | | Join Date: Jan 2007 Location: Southern California USA
Posts: 4,091
| | | re: How to sort the data?
another way using a hash of arrays: - @data = qw(man women man man women man man man);
-
my %hash;
-
my $i;
-
foreach my $thing (@data) {
-
push @{$hash{$thing}},$i++;
-
}
-
for (keys %hash) {
-
print "$_:", join(',',@{ $hash{$_} }), "\n";
-
}
| | Newbie | | Join Date: Jul 2008
Posts: 5
| | | re: How to sort the data?
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
| | Member | | Join Date: Jul 2007
Posts: 35
| | | re: How to sort the data? Quote:
Originally Posted by alampally 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 -
@data=('man', 'women', 'man', 'man',
-
'women', 'man', 'man', 'man');
-
my $str;
-
my $women;
-
for ($i = 1;$i <=$#data+1;$i++)
-
{
-
$str.= $i if $data[$i-1]=~ /man/;
-
$women.= $i if $data[$i-1]=~ /women/;
-
-
}
-
print "$str:man\n";
-
print "$women:women";
-
| | Member | | Join Date: Jul 2008
Posts: 70
| | | re: How to sort the data?
Thanks for the help.
|  | | | | /bytes/about
We are a network of experts and professionals in IT and software development that help one another with answers to tough questions and share insights.
Get the best answers to your questions from over 226,501 network members.
|