Perl 字符串操作 以及 自定義排序

  1. #!/usr/bin/perl -w  

  2. #########################################################################  

  3. # File Name: test6.pl  

  4. #########################################################################  

  5.   

  6. #index(str,substr,position),在大字符串中查找  

  7. #position可以設置起始位置,返回位置數  

  8. my $stuff = "hello word";  

  9. my $where = index($stuff, "wor");  

  10. print "where: $where\n";  

  11.   

  12. my $where1 = index($stuff, "w");  

  13. print "where1: $where1\n";  

  14.   

  15. my $where2 = index($stuff, "w", 6);  

  16. print "where2: $where2\n";  

  17.   

  18. # substr($string, $init_position, $length) 處理部分字符串  

  19. $substr1 = substr("hello world", 6, 5); #得到substr1: world  

  20. print "substr1: $substr1\n";  

  21. #可以作替換字符串使用  

  22. substr($substr1,0,0)="hello ";  

  23. print "substr1: $substr1\n"#substr1: hello world  

  24. #替換功能也可以使用第四個參數  

  25. $string = "hello world";  

  26. substr($string, 0, 5, "xxxxx");  

  27. print "string: $string\n";  

  28.   

  29. #sprintf 格式化數據   

  30. $year = "2014";  

  31. $month = 8;  

  32. $day = 2.0;  

  33. $data_tag = sprintf("%s/%d/%.3f", $year, $month, $day);  

  34. print "data_tag: $data_tag\n"#data_tag: 2014/8/2.000  

  35.   

  36. #排序  

  37. #排序子函數,按數字排序  

  38. sub by_num{  

  39.     $a <=> $b  

  40. }  

  41. @nums = (1,4,22,5,33,10,12);  

  42. print "nums: @nums\n";  

  43. @result1 = sort @nums;  

  44. print "result1: @result1\n"#只會把數字當作字符排序  

  45. @result2 = sort by_num @nums;  

  46. print "result2: @result2\n"#會根據數值大小進行排序  

  47.   

  48. #對hash排序  

  49. my %socre = (  

  50.     "kevin" => 100,  

  51.     "xiang" => 50,  

  52.     "jie" => 150,  

  53.     "xxx" => 1,  

  54.     "yyy" => 50  

  55. );  

  56. @socre1 = %socre;  

  57. print "socre1: @socre1\n"#socre1: xiang 50 jie 150 kevin 100 xxx 1 yyy 50  

  58.   

  59. #排序子函數,根據value 從小到大   

  60. #如果是數字直接用 <=> 如果是字符串用 cmp  

  61. sub by_socre_value{  

  62.     $socre{$a} <=> $socre{$b}  

  63. }  

  64. @socre2 = sort by_socre_value keys %socre;  

  65. print "socre2: @socre2\n"#socre2: xxx xiang yyy kevin jie  

  66.   

  67.   

  68. %socre = (  

  69.     "kevin" => 100,  

  70.     "xiang" => 50,  

  71.     "jie" => 150,  

  72.     "xxx" => 1,  

  73.     "yyy" => 50  

  74. );  

  75. #根據value 從小到大, 如果value相同,則根據key字母反序  

  76. #如果還有很多個條件,可以加or再限制  

  77. sub by_socre_value_and_key{  

  78.     $socre{$a} <=> $socre{$b}  

  79.     or  

  80.     $b cmp $a;  

  81. }  

  82. @socre3 = sort by_socre_value_and_key keys %socre;  

  83. print "socre3: @socre3\n"#socre3: xxx yyy xiang kevin jie  




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章