Tuesday, 15 May 2012

Sorting Array in Perl -


I thought I could do it in the way described below. However, when I sort it like this, the output is hexadecimal value, the string is rather than pointing to "item" in the array @ menu. I want to sort it with "item-name" to get it

  my @ menuu = ({item = & gt; "blazer", price => 100, color = & Gt; "Brown"}, {item = & gt; "jeans", value => 50, color => gt; "blue"}, {item = & gt; "shawl", price => 30, Color = & gt; "red"}, {item = & gt; "suit", value = & gt; 40, color = & gt; "black"}, {item => "top", value = & Gt; 25, color = & gt; "white"},); My @test = sort {item} @ menu; Foreign (@Test) {Print $ _; }  

prints your print $ _ string value Each hash context, you will get something like HASH (0x1d33524) . You have to print the fields of each hash, which you are interested in.

In addition, you need a proper comparison expression within the sort block, giving the name of a hash key will not be useful.

  Use strict; Use warnings; My @ menu = ({item = & gt; 'blazer', price => 100, color = & gt; 'brown'}, {item = & gt; 'jeans', value => 50, color = & Gt; Blue '}, {item = & gt; shawl', value = & gt; 30; color = & gt; 'red'}, {item = & gt; 'suit', value = & gt; 40 , Color = & gt; 'black'}, {item = & gt; 'top', price => 25, color = & gt; 'white'}); My @ test = sort {$ a-> gt; {Item} cmp $ b- & gt; {Item}} @ menu; (@Test) {print "@ {$ _} {qw / item value color}} \ n"; Blazer 100 Brown Jeans 50 Blue Shawls 30 Red Suites 40 Black Top 25 White  

Output

  / Pre >    

>

  Use strict; Use warnings; My @ menu = ({item = & gt; 'blazer', price => 100, color = & gt; 'brown'}, {item = & gt; 'jeans', value => 50, color = & Gt; Blue '}, {item = & gt; shawl', value = & gt; 30; color = & gt; 'red'}, {item = & gt; 'suit', value = & gt; 40 , Color = & gt; 'black'}, {item = & gt; 'top', price => 25, color = & gt; 'white'}); My @test = type map {$ _- & gt; {Item}} @ menu; Print "$ _ \ n" for print;  

Output

  Blurzer jeans shawl suit top  

No comments:

Post a Comment