Perl 字符串操作

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


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

  3.   

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

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

  6. my $stuff = "hello word";  

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

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

  9.   

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

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

  12.   

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

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

  15.   

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

  17. $substr1 = substr("hello world"65); #得到substr1: world  

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

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

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

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

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

  23. $string = "hello world";  

  24. substr($string, 05"xxxxx");  

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

  26.   

  27. #sprintf 格式化數據   

  28. $year = "2014";  

  29. $month = 8;  

  30. $day = 2.0;  

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

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

  33.   

  34. #排序  

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

  36. sub by_num{  

  37.     $a <=> $b  

  38. }  

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

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

  41. @result1 = sort @nums;  

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

  43. @result2 = sort by_num @nums;  

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

  45.   

  46. #對hash排序  

  47. my %socre = (  

  48.     "kevin" => 100,  

  49.     "xiang" => 50,  

  50.     "jie" => 150,  

  51.     "xxx" => 1,  

  52.     "yyy" => 50  

  53. );  

  54. @socre1 = %socre;  

  55. print "socre1: @socre1\n"#socre1: XUE 50 HUI150 HAPPY 100 xxx 1 yyy 50  

  56.   

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

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

  59. sub by_socre_value{  

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

  61. }  

  62. @socre2 = sort by_socre_value keys %socre;  

  63. print "socre2: @socre2\n"#socre2: xxx happy yyy xue hui

  64.   

  65.   

  66. %socre = (  

  67.     "lisan" => 100,  

  68.     "zhong" => 50,  

  69.     "gao" => 150,  

  70.     "xxx" => 1,  

  71.     "yyy" => 50  

  72. );  

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

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

  75. sub by_socre_value_and_key{  

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

  77.     or  

  78.     $b cmp $a;  

  79. }  

  80. @socre3 = sort by_socre_value_and_key keys %socre;  

  81. print "socre3: @socre3\n"#socre3: xxx yyy xue hui kuaile




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