Advertisement
Guest User

Untitled

a guest
Oct 6th, 2018
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 24.01 KB | None | 0 0
  1. This Perl programming tutorial is a great scripting guide to help you fully understand Perl script. Find Perl tutorials and programming examples to master your knowledge of Perl Scripting.
  2.  
  3. 1. Using The Perl interpreter
  4.  
  5. 1.1. Find Perl Interpreter
  6.  
  7. which perl
  8.  
  9. 1.2. Implicit Execution
  10.  
  11. NOTE:Every script starts with shebang:"#!" which is not read as a comment. First line is also a place where you put your interpreter which in this case is perl.
  12. #!/usr/bin/perl print "Perl Programming\n";
  13. Make Perl Script Executable:
  14.  
  15. chmod +x perl_script.pl
  16.  
  17.  
  18. 1.3. Explicit Execution
  19.  
  20. print "Perl Programming\n";
  21. Make Perl Script Executable:
  22. chmod +x perl_script.pl
  23.  
  24. 2. Simple Perl script
  25.  
  26. #!/usr/bin/perl # print "Perl Programming Tutorial\n";
  27.  
  28. 3. Current path to Perl modules
  29.  
  30. List all available current paths to perl modules:
  31. perl -e 'print "@INC" . "\n";'
  32.  
  33. 4. Variables
  34.  
  35. $ - Scalar Variable
  36. % - Hash Variable
  37. @ - Array
  38. & - Subroutines
  39. 4.1. Using Perl default variable $_
  40.  
  41. #!/usr/bin/perl
  42. $_ = "Perl Programming default variable.\n";
  43. print;
  44.  
  45. 4.2. Defined Function
  46.  
  47. #!/usr/bin/perl
  48.  
  49. # declare perl scalar do but not define value
  50. $perl_scalar;
  51. #we can use conditional operator '?:' to test perl defined funtion
  52. $variable = defined($perl_scalar) ? "Variable \$perl_scalar is Defined!"
  53. : "Variable \$perl_scalar is NOT Defined!";
  54. print $variable."\n";
  55. # declare perl scalar with value
  56. $perl_scalar="perl";
  57. $variable = defined($perl_scalar) ? "Variable \$perl_scalar is Defined!"
  58. : "Variable \$perl_scalar is NOT Defined!";
  59. print $variable."\n";
  60.  
  61. 4.3. Scalar variable
  62.  
  63. #!/usr/bin/perl
  64. #Scalars hold just single data type: string, number or perl reference
  65. #Scalars definition in Perl
  66. $scalar_number = -5;
  67. $scalar_string1 = "In PERL Scalars are always referenced with \x24 in front of each variable name. ";
  68. $scalar_string2 = "5 items";
  69. #Undescore can be use for big numbers
  70. $scalar_milion = 1_000_000;
  71. #Print scalar values
  72. print $scalar_number."\n";
  73. print $scalar_string1."\n";
  74. print $scalar_string2."\n";
  75. print $scalar_milion."\n";
  76. #perl scalar addition
  77. print $scalar_number + $scalar_milion."\n";
  78.  
  79. 4.3.1. Single-Quoted Strings
  80. #!/usr/bin/perl
  81.  
  82. #Single-Quoted scalar strings
  83. $scalar_string1='perl';
  84. print "String 1: ".$scalar_string1."\n";
  85. $scalar_string2='#!/usr/bin/perl';
  86. print "String 2: ".$scalar_string2."\n";
  87. $scalar_string3='Perl
  88. Programming
  89. Tutorial';
  90. print "String 3: ".$scalar_string3."\n";
  91. $scalar_string4='Perl\n';
  92. print "String 4: ".$scalar_string4."\n";
  93. $scalar_string5='\'\'\\';
  94. print "String 5: ".$scalar_string5."\n";
  95. $scalar_string6='';
  96. print "String 6: ".$scalar_string6."\n";
  97. $scalar_string7='I\'m reading Perl Programming Tutorial';
  98. print "String 7: ".$scalar_string7."\n";
  99.  
  100. 4.3.2. Double-Quoted Strings
  101. #!/usr/bin/perl
  102. #Double-Quoted scalar strings
  103. $scalar_string1="perl";
  104. print "String 1: ".$scalar_string1."\n";
  105. $scalar_string2="#!/usr/bin/perl";
  106. print "String 2: ".$scalar_string2."\n";
  107. $scalar_string3="Perl
  108. Programming
  109. Tutorial";
  110. print "String 3: ".$scalar_string3."\n";
  111. $scalar_string4="Perl\n";
  112. print "String 4: ".$scalar_string4."\n";
  113. $scalar_string5="\'\'\\\"";
  114. print "String 5: ".$scalar_string5."\n";
  115. $scalar_string6="";
  116. print "String 6: ".$scalar_string6."\n";
  117. # add "!" ASCII character in octal form !=041
  118. $scalar_string7="I\'m reading Perl Programming Tutorial \041";
  119. print "String 7: ".$scalar_string7."\n";
  120. # add "@" ASCII character in hexadecimal form @=40
  121. $scalar_string8="Any feedback about this \uperl \uprogramming
  122. \ututorial to: web\x40\lL\LINUXCONFIG.ORG\E";
  123. print "String 8: ".$scalar_string8."\n";
  124.  
  125. 4.3.3. String Operators
  126. #!/usr/bin/perl
  127.  
  128. #Scalar string Operators
  129. $scalar_string1="pe"."rl";
  130. print "String 1: ".$scalar_string1."\n";
  131. $scalar_string2="Perl Programming Tutorial " x (1+1);
  132. print "String 2: ".$scalar_string2."\n";
  133. $scalar_string3="3"."\ttabs" x 3;
  134. print "String 3: ".$scalar_string3."\n";
  135. $scalar_string4="Perl\x20".'Programming '."Tutorial";
  136. print "String 4: ".$scalar_string4."\n";
  137. $scalar_string5=9x5;
  138. print "String 5: ".$scalar_string5."\n";
  139.  
  140. 4.3.4. Non-Decimal Integers
  141. #!/usr/bin/perl
  142.  
  143. #perl binary integer
  144. $hash_binary_integer = 0b10000;
  145. #perl octal integer
  146. $hash_octal_integer = 020;
  147. #perl hexadecimal integer
  148. $hash_hexadecimal_integer1 = 0x10;
  149. $hash_hexadecimal_integer2 = 0x124c_78_aa;
  150.  
  151. print $hash_octal_integer."\n";
  152. print $hash_binary_integer."\n";
  153. print $hash_hexadecimal_integer1."\n";
  154. print $hash_hexadecimal_integer2."\n";
  155.  
  156. 4.3.5. Scalar Constant Variable
  157. #!/usr/bin/perl
  158.  
  159. $ordinary_scalar = 5;
  160. $ordinary_scalar = 10;
  161.  
  162. print $ordinary_scalar."\n";
  163.  
  164. #perl constant declaration
  165. *SCALAR_CONSTANT = 5;
  166. $SCALAR_CONSTANT = 10;
  167.  
  168. 4.3.6. String And Numeric comparison Operators
  169. Comparison String Numeric
  170. Equal eq ==
  171. Not Equal ne !=
  172. Less than lt <
  173. Greater than gt >
  174. Less than or equal le <=
  175. Greater than or equal ge >=
  176. #!/usr/bin/perl
  177. # String comparison
  178. if ( 'Perl' eq 'perl' ) {
  179. print "TRUE\n";
  180. } else {
  181. print "FALSE\n";
  182. }
  183.  
  184. # Numeric comparison
  185. if ( '2.4' != '2.6' ) {
  186. print "TRUE\n";
  187. } else {
  188. print "FALSE\n";
  189. }
  190.  
  191. 4.4. Lists
  192.  
  193. #!/usr/bin/perl
  194.  
  195. #Lists definition in Perl
  196. print ("Perl ","programming ","Tutorial","\n");
  197.  
  198. 4.5. Arrays
  199.  
  200. 4.5.1. Create and print array
  201. #!/usr/bin/perl
  202.  
  203. #CREATE AN ARRAY
  204. @perl_array1 = qw(Perl Programming Tutorial );
  205. @perl_array2 = ("Perl ", "Programing ", "Tutorial", "\n");
  206. @perl_array3 = (1 .. 3);
  207. $perl_array4[0] = "Perl ";
  208. $perl_array4[1] = "Programming ";
  209. $perl_array4[2] = "Tutorial";
  210. $perl_array4[50] = "\n";
  211.  
  212. #ADD ELEMENTS TO AN ARRAY
  213. $perl_array1[3] = "\n";
  214.  
  215. #PRINT ARRAY
  216. print @perl_array1;
  217. print @perl_array2;
  218. print @perl_array3;
  219. print $perl_array1[3];
  220. print @perl_array4;
  221. # What index has a last element of an array
  222. print "Last element of perl_array4 has index: " . $#perl_array4 ."\n";
  223.  
  224. 4.5.2. Push and Pop Arrays
  225. #!/usr/bin/perl
  226.  
  227. # CREATE AN ARRAY
  228. @perl_array = (1 .. 3);
  229.  
  230. # PUSH NEW ELEMENT TO THE AND OF AN ARRAY
  231. push(@perl_array, "\n");
  232.  
  233. # PRINT ARRAY
  234. print @perl_array;
  235.  
  236. # POP LAST ELEMENT FROM AN ARRAY
  237. $perl_scalar = pop(@perl_array);
  238. print @perl_array;
  239.  
  240. # PRINT NEW LINE
  241. print $perl_scalar;
  242.  
  243. 4.5.3. Determine The Length of an Array
  244. #!/usr/bin/perl
  245.  
  246. #CREATE AN ARRAY
  247. @perl_array = (1 .. 3);
  248. $number_of_elements = @perl_array;
  249. print "\@perl_array has: " . $number_of_elements . " elements.\n";
  250. print "\@perl_array has: " . scalar(@perl_array) . " elements.\n";
  251.  
  252. 4.5.4. Merge and Append Arrrays
  253. #!/usr/bin/perl
  254.  
  255. #CREATE AN ARRAY
  256.  
  257. @perl_array1 = (".\n", "easy", "very ") ;
  258. @perl_array2 = ("is ", "Programming ", "Perl ");
  259. @perl_array3 = (@perl_array1, @perl_array2);
  260. # REVERSING ELEMENTS
  261. print reverse @perl_array3;
  262.  
  263. 4.5.5. Sort Arrays
  264. #!/usr/bin/perl
  265.  
  266. #CREATE AN ARRAY
  267.  
  268. @perl_array = (3, 4, 1, 2);
  269. @sorted_array1 = sort @perl_array;
  270. @sorted_array2 = sort {$b <=> $a} @perl_array;
  271.  
  272. print "@sorted_array1 \n";
  273. print "@sorted_array2 \n";
  274.  
  275. 4.5.6. Delete Element from an Array
  276. #!/usr/bin/perl
  277.  
  278. #CREATE AN ARRAY
  279. @perl_array = (1, 2, 3, 4);
  280. # CHECK IF THE ARRAY ELEMENT EXISTS
  281. if (exists($perl_array[2])) {
  282. delete $perl_array[2];
  283. } else {
  284. print "Array element is mising!\n"
  285. }
  286. print @perl_array, "\n";
  287.  
  288. 4.6. Hash
  289.  
  290. 4.6.1. Create Hash
  291. #!/usr/bin/perl
  292.  
  293. # CREATE HASH
  294. %perl_hash = (
  295. browser => iceweasel,
  296. # you can also use comma instead of arrow operator
  297. os , linux,
  298. );
  299. # PRINT HASH ELEMENT
  300. print "$perl_hash{'browser'}\n";
  301.  
  302. 4.6.2. Add Element to a Hash
  303. #!/usr/bin/perl
  304.  
  305. # CREATE HASH
  306. %perl_hash = (
  307. browser => iceweasel,
  308. # you can also use comma instead of arrow operator
  309. os , linux,
  310. );
  311. # PRINT HASH ELEMENT
  312. print "$perl_hash{'browser'}\n";
  313.  
  314. # ADD ELEMENTS TO A HASH
  315. %perl_hash = (%perl_hash, programming, perl);
  316.  
  317. # PRINT ALL ELEMENTS
  318. print join(" ", %perl_hash). "\n";
  319.  
  320. 4.6.3. Print Hash
  321. #!/usr/bin/perl
  322.  
  323. # CREATE HASH
  324. %perl_hash = qw(
  325. ssh 22
  326. http 80
  327. https 443
  328. telnet 23
  329. postgres 5432
  330. );
  331.  
  332. while (($hash_key, $hash_value) = each %perl_hash ){
  333. print "$hash_key uses port $hash_value\n";
  334. }
  335.  
  336. 4.6.4. Merging Hashes
  337. #!/usr/bin/perl
  338.  
  339. # CREATE HASH
  340. %perl_hash1 = qw(
  341. Debian deb
  342. );
  343. %perl_hash2 = qw(
  344. RedHat rpm
  345. );
  346. #MERGE HASHES
  347. %perl_hash3 = (%perl_hash1, %perl_hash2);
  348.  
  349. while (($hash_key, $hash_value) = each %perl_hash3 ){
  350. print "$hash_key: $hash_value\n";
  351. }
  352.  
  353. 5. Perl Regular Expressions
  354.  
  355. 5.1. Regular Expressions and Special Characters
  356.  
  357. \D Matches non-digit character \d Matches digit character \E End case modification
  358. \e escape \f Form feed \L Matches lowercase until \E found
  359. \l Next character lower case \n New line \r Return
  360. \S Match a non-white space character \s Match a white space character \t Match tab
  361. \U Match upper case until \E found \u Next character uppercase \W Match non-word
  362. \w Match word \Q Quote pattern metacharacter until \E found
  363. 5.2. Match Characters
  364.  
  365. #!/usr/bin/perl
  366.  
  367. foreach(@ARGV) {
  368. # Regex Match lower case and upper case character "p" ( ignores alphabetic case )
  369. if (m/p/i) {$p1++;}
  370. # Regex Match lower case character "p" only
  371. if (m/p/) {$p2++;}
  372. # Regex Match two characters "ex" and ignore alphabetic case
  373. if (m/ex/i) {$ex++;}
  374. }
  375. print "p1=$p1\np2=$p2\nex=$ex\n";
  376.  
  377. 5.3. Substitution
  378.  
  379. Sample File: perl_regex.txt
  380. # Perl Regular Expressions #
  381. # Character Substitute #
  382. #!/usr/bin/perl
  383.  
  384. open (FILEHANDLE, $ARGV[0]) || die "Problems opening file";
  385.  
  386. @file=;
  387.  
  388. foreach(@file) {
  389. # Substitute "#" with "$" and work globally for each instance found
  390. # NOTE: all metcharacters needs to bu escaped with "\" like in
  391. # this case "$" is escaped "\$" to be read literally
  392. # Meta characters are: \ | { [ ( ) ^ $ * + ? .
  393. s/\#/\$/g;
  394. # Substitute upper case "E" with lower case "e"
  395. s/E/e/;
  396. # Substitute first match of " " with "_"
  397. s/\s/\_/;
  398. # Substitute first match of " " with "\"
  399. # Note: Is your choice which substitute form you use s/// or s|||
  400. s|\s|\\|;
  401. print;
  402. }
  403.  
  404. 5.3.1. Substitution with evaluation
  405. In case a string is to be substituted with the output of a function call - rather than static text we can use the evaluation modifier (/e) which evaluates the right hand side as code, rather than a string.
  406. #!/usr/bin/perl
  407.  
  408. my $text_eval = my $text_noeval = "Here is some texxxt.\n";
  409. $text_noeval =~ s/(xx+)/'(x^'.length($1).')'/;
  410. print "Text without evaluation:".$text_noeval."\n";
  411. $text_eval =~ s/(xx+)/'(x^'.length($1).')'/e;
  412. print "Text with evaluation:".$text_eval."\n";
  413. linuxconfig.org:~$ ./subst_eval.pl
  414. Text without evaluation:Here is some te'(x^'.length(xxx).')'t.
  415.  
  416. Text with evaluation:Here is some te(x^3)t.
  417. 5.4. Translation
  418.  
  419. #!/usr/bin/perl
  420.  
  421. $string="uSe REgular Expression claSSes TO tRanslatE FroM upPEr case tO lOwER caSe chArActErs";
  422. # Use perl to convert string characters from upper case to lower case
  423. $string =~ tr/A-Z/a-z/;
  424. print "$string\n";
  425. # Use perl to convert string characters from lower case to upper case
  426. $string =~ tr/a-z/A-Z/;
  427. print "$string\n";
  428.  
  429. 5.5. Classes
  430.  
  431. A regular expression surrounded in square brackets is called a character class which matches any single character described by the regular expression.
  432. #!/usr/bin/perl
  433. foreach(@ARGV) {
  434. # Substitute all characters "except ^" upper case characters and character "e" with "#"
  435. s/[^A-Ze]/\#/g; print;
  436. }
  437. print "\n";
  438.  
  439. 5.6. Quantifiers
  440.  
  441. #!/usr/bin/perl
  442.  
  443. @array1 = @ARGV;
  444. @array2 = @ARGV;
  445.  
  446. print "\@array1 = ";
  447. foreach(@array1) {
  448. # Substitute at least 3 "s" characters
  449. s/s{3,}/SS/g; print;
  450. }
  451. print "\n\@array2 = ";
  452. foreach(@array2) {
  453. # Substitute one or more "s" characters
  454. s/s+/S/g; print;
  455. }
  456. print "\n";
  457.  
  458. 5.7. Assertion
  459.  
  460. #!/usr/bin/perl
  461.  
  462. foreach(@ARGV) {
  463. # Substitute character "a" and the end of the string with "$"
  464. s/a$/\$/g;
  465. # Substitute character "a" and the beginning of the string with "^"
  466. s/^a/\^/g;
  467. print;
  468. }
  469. print "\n";
  470.  
  471. 5.8. Multiple Match
  472.  
  473. #!/usr/bin/perl
  474. # /g match globally
  475. $text="We want to improve your Perl Regular Expressions skills.";
  476. print "Number of Substitutions made: " . ($text =~ s/e/E/);
  477. print "\n$text\n";
  478.  
  479. $text="We want to improve your Perl Regular Expressions skills.";
  480. print "Number of Substitutions made: " . ($text =~ s/e/E/g);
  481. print "\n$text\n";
  482.  
  483. 5.9. Regular Expression Extention
  484.  
  485. (?=) Matches If would match next
  486. (?!) Matches If would NOT match next
  487. (?<=) Matches If would match just before
  488. (?) Matches If would NOT match just before
  489. (?#) = Comment
  490. #!/usr/bin/perl
  491.  
  492. $_="We want you to improve your Perl Regular Expressions skills.";
  493. # Replace space with "#" if it is followed by "to"
  494. s/\s(?=to)/#/g;
  495. print "$_\n";
  496. # Replace space with "_" if it is NOT followed by "s"
  497. s/\s(?!s)/_/g;
  498. print "$_\n";
  499.  
  500. 5.10. Grouping
  501.  
  502. #!/usr/bin/perl
  503.  
  504. $a=$ARGV[0];
  505.  
  506. if ($a =~ /(.*)@(.*)\.(.*)/) {
  507. print "$1\n$2\n$3\n";
  508. }
  509.  
  510. 6. Perl Subroutines
  511.  
  512. 6.1. Create Simple Perl Subroutine
  513.  
  514. #!/usr/bin/perl
  515. # Lets create subroutine which we can use to check for presence of number in the string.
  516. # Name of the subroutine is numbers_in_string
  517. sub numbers_in_string
  518. {
  519. if ($mystring =~ /[0-9]/) {
  520. print "Supplied string contains numbers!\n";
  521. } else {
  522. print "Supplied string does NOT contain numbers!\n";
  523. }
  524. }
  525. # declare global scope variable which means that this variable can be accessed from anywhere in this code.
  526. $mystring="number one";
  527. # perl subroutine calls
  528. numbers_in_string;
  529. $mystring="number 1";
  530. # perl subroutine calls
  531. numbers_in_string;
  532. numbers_in_string($mystring);
  533.  
  534. 6.2. Pass and Return Values
  535.  
  536. #!/usr/bin/perl
  537.  
  538. sub perl_addition {
  539. # all variable passed to the perl subroutines are stored in special @_ variable
  540. ($number1, $number2) = @_;
  541. # return the result
  542. return $number1 + $number2 ;
  543. }
  544. # print result by calling perl_addition() subroutine
  545. print "Number1 + Number2 = " . perl_addition(4, 2) . "\n";
  546.  
  547. 7. Perl operators
  548.  
  549. 7.1. Precedence of Perl operators
  550.  
  551. Operators Associativity
  552. Parentheses and List operators left
  553. -> left
  554. ++ -- n/a
  555. ** Right
  556. ! ~ \ unary+ unary- left
  557. =~ !~ left
  558. * / % x left
  559. + - . left
  560. << >> left
  561. Named unary operators and file test operators n/a
  562. < > <+ >+ lt gt le ge n/a
  563. == != <=> eq ne cmp n/a
  564. & left
  565. | ^ left
  566. && left
  567. || left
  568. .. ... n/a
  569. ?: right
  570. =+= -+ *= right
  571. , => left
  572. Rightward List operators n/a
  573. not right
  574. and left
  575. or xor left
  576. #!/usr/bin/perl
  577.  
  578. print 1 + 2 * 3 + 4 . "\n";
  579. print ((1 + 2) * (3 + 4));
  580. print "\n";
  581. # Print as a function or operator
  582. print ((5 + 5 ) * 5); print "\n";
  583. print (5 + 5 ) * 5; print "\n";
  584. # Use unary + operator to tell perl
  585. # that we are not making print() function call
  586. # but rather using parentheses as a precedence
  587. print +(5 + 5 ) * 5; print "\n";
  588.  
  589. 7.2. Arrow operator
  590.  
  591. #!/usr/bin/perl
  592.  
  593. $perl_hash{browser} = iceweasel;
  594. $perl_hash_reference= \%perl_hash;
  595. print $perl_hash_reference->{browser} . "\n";
  596.  
  597. 7.3. Increment and Decrement operators
  598.  
  599. #!/usr/bin/perl
  600.  
  601. $perl_scalar1 = 1;
  602. $perl_scalar2 = 2;
  603. $perl_scalar3 = 'p';
  604. $perl_scalar4 = 'PERL';
  605.  
  606. print $perl_scalar1++ . " , ";
  607. print $perl_scalar1 . " , ";
  608. print ++$perl_scalar3 . " , ";
  609. print ++$perl_scalar4 . "\n";
  610.  
  611. 8. Loops
  612.  
  613. 8.1. Perl for loop
  614.  
  615. #!/usr/bin/perl
  616.  
  617. # Definition of perl for loop
  618. for($for_loop=0;$for_loop<=4;$for_loop++) {
  619. print "for loop value is:".$for_loop."\n";
  620. }
  621.  
  622. 8.2. Perl while loop
  623.  
  624. #!/usr/bin/perl
  625. #
  626.  
  627. $while_loop=5;
  628.  
  629. # Definition of perl while loop
  630. while ($while_loop>=0) {
  631. print "while loop value is:".$while_loop."\n";
  632. $while_loop--;
  633. }
  634.  
  635. 8.3. Perl until loop
  636.  
  637. #!/usr/bin/perl
  638. #
  639. $until_loop=5;
  640.  
  641. # Definition of perl until loop
  642. until ($until_loop==0) {
  643. print "until loop value is:".$until_loop."\n";
  644. $until_loop--;
  645. }
  646.  
  647. 8.4. Perl foreach loop
  648.  
  649. #!/usr/bin/perl
  650.  
  651. #Declare array
  652.  
  653. @foreach_loop = (" Tutorial\n" , " Scripting" , "Perl" ) ;
  654. foreach $count (reverse @foreach_loop) {
  655. print $count;
  656. }
  657.  
  658. 9. Getting User Input
  659.  
  660. #!/usr/bin/perl
  661.  
  662. # getting user input
  663. $user_input = ; # also possible to use just (<>)
  664. print $user_input;
  665. # clear user input and remove new line character
  666. chomp($user_input);
  667. print $user_input ." ";
  668. [[Image:perl_user_input.gif]]
  669. 9.1. Reading Command Line Arguments
  670.  
  671. #!/usr/bin/perl
  672. # reading command line arguments with perl
  673. # @ARGV is Perl build-in array which
  674. # contains all arguments passed during command line execution
  675. print join(" ", @ARGV);
  676.  
  677. print "\n" . $ARGV[0] . $ARGV[1] . $ARGV[2] . $ARGV[3] . $ARGV[4] . $ARGV[5] . "\n";
  678.  
  679. 10. File Handling
  680.  
  681. 10.1. Read File Passed from the Command line
  682.  
  683. #!/usr/bin/perl
  684.  
  685. # read all files passed by command line as a arguments.
  686. while (<>) {
  687. print;
  688. }
  689.  
  690. 10.2. Open File for Read and Write
  691.  
  692. #!/usr/bin/perl
  693.  
  694. # Create filehandle for write called WFILEHANDLE for file perl.txt
  695. # if the file does not exists it will be created.
  696. open (WFILEHANDLE, ">perl.txt") or die ("Cannot open perl.txt .\n");
  697.  
  698. # Insert data to perl.txt
  699. print WFILEHANDLE "Perl Programming Tutorial";
  700.  
  701. #Close filehandle.
  702. close (WFILEHANDLE);
  703.  
  704. # Create filehandle for read called RFILEHANDLE for file perl.txt
  705. open (RFILEHANDLE, "
  706.  
  707. # read file and print to
  708. while () {
  709. print;
  710. }
  711. print "\n";
  712.  
  713. 10.3. Determine Number of Lines in a File
  714.  
  715. #!/usr/bin/perl
  716.  
  717. open(FILEHANDLE, $ARGV[0]) or die ("Could not open a given file");
  718.  
  719. @lines=;
  720. print "Number of Lines in the file: " . scalar(@lines) . "\n";
  721. # Perl can Print particular line from the file
  722. print "Line number 23: ". $lines[22] . "/n";
  723.  
  724. 10.4. Determine Number of Characters in a File
  725.  
  726. #!/usr/bin/perl
  727.  
  728. open(FILEHANDLE, $ARGV[0]) or die ("Could not open a given file");
  729. my $input =0;
  730. while (defined($char = getc FILEHANDLE)) {
  731. $input++;
  732. }
  733. print "Number of characters: " . $input . "\n";
  734. close FILEHANDLE;
  735.  
  736. 10.5. Seek position within a File
  737.  
  738. #!/usr/bin/perl
  739.  
  740. # seek is helpful perl function, especially with huge files, where sequential access
  741. # may be time consuming and may require lots of processing power. Seek provides quick random access.
  742. # 0 -set the new position in bytes to POSITION
  743. # 1 -set the current position plus POSITION
  744. # 2 -set the new position EOF plus POSITION (often negative)
  745. # use seek function to set position 20000 bytes
  746.  
  747. open(FILEHANDLE, $ARGV[0]) or die ("Could not open a given file !!");
  748. seek FILEHANDLE, 20000,0;
  749. # use perl tell function to check file position.
  750. print tell FILEHANDLE;
  751. print " -> seek FILEHANDLE, 20000,0 \n";
  752. # Add another 36 bytes
  753. seek FILEHANDLE, 36,1;
  754. print tell FILEHANDLE;
  755. print " -> seek FILEHANDLE, 36,1 \n";
  756. # Return position to byte 10
  757. seek FILEHANDLE, 10,0;
  758. print tell FILEHANDLE;
  759. print " -> seek FILEHANDLE, 10,0 \n";
  760. # Set position to the end of the file (eof)
  761. seek FILEHANDLE, 0,2;
  762. print tell FILEHANDLE;
  763. print " -> seek FILEHANDLE, 0,2 \n";
  764.  
  765. close FILEHANDLE;
  766.  
  767. 11. Simple Perl Arithmetics
  768.  
  769. #!/usr/bin/perl
  770.  
  771. #perl addition
  772. $addition=5+5.3;
  773. print "Perl Addition:\n5 + 5 = ".$addition."\n";
  774.  
  775. #perl subtraction
  776. $subtraction=100-23;
  777. print "Perl Subtraction:\n100 - 23 = ".$subtraction."\n";
  778.  
  779. #perl multiplication
  780. $multiplication=3*9;
  781. print "Perl Multiplication:\n3 x 9 = ".$multiplication."\n";
  782.  
  783. #perl division
  784. $division=45/5;
  785. print "Perl Division:\n45 : 5 = ".$division."\n";
  786.  
  787. #perl modulus
  788. $modulus=10%3;
  789. print "Perl Modulus:\n10 % 3 = ".$modulus."\n";
  790.  
  791. #perl exponential
  792. $exponential=3**4;
  793. print "Perl Exponential:\n3 ** 4 = ".$exponential."\n";
  794.  
  795. 12. Perl Octal, Hexadecimal, And Decimal Conversions
  796.  
  797. #!/usr/bin/perl
  798.  
  799. print "\n";
  800.  
  801. #perl bin to dec
  802. #PERL CONVERSION FROM BINARY TO DECIMAL
  803. $decimal_number = 0b10010110;
  804. print "Binary number 10010110 is " . $decimal_number . " in decimal.\n";
  805.  
  806. #perl dec to bin
  807. #PERL CONVERSION FROM DECIMAL TO BINARY
  808. $decimal_number = 23451;
  809. $binary_number = unpack("B32", pack("N", $decimal_number));
  810. print "Decimal number " . $decimal_number . " is " . $binary_number .
  811. " in binary.\n\n";
  812.  
  813. #perl oct to dec
  814. #PERL CONVERSION FROM OCTAL TO DECIMAL
  815. $octal_number = 224;
  816. $decimal_number = oct($octal_number);
  817. print "Octal number " . $octal_number . " is " . $decimal_number . "
  818. in decimal.\n";
  819. #perl dec to oct
  820. #PERL CONVERSION FROM DECIMAL TO OCTAL
  821. $decimal_number = 8;
  822. $octal_number = sprintf("%o",$decimal_number);
  823. print "Decimal number " . $decimal_number . " is " . $octal_number . "
  824. in octal.\n\n";
  825.  
  826. #perl hex to dec
  827. #PERL CONVERSION FROM HEXADECIMAL TO DECIMAL
  828. $hexadecimal_number = "F1";
  829. $decimal_number = hex($hexadecimal_number);
  830. print "Hexadecimal number " . $hexadecimal_number . " is " .
  831. $decimal_number . " in decimal.\n";
  832.  
  833. #perl dec to hex
  834. #PERL CONVERSION FROM DECIMAL TO HEXADECIMAL
  835. $decimal_number= 333;
  836. $hexadecimal_number = sprintf("%x", $decimal_number);
  837. print "Decimal number " . $decimal_number . " is " .
  838. $hexadecimal_number . " in hexadecimal.\n\n";
  839.  
  840. 13. Create Perl Package
  841.  
  842. Here is an example of simple perl package: perl_package.pm
  843. # DECLARE PERL PACKAGE
  844. package perl_package;
  845.  
  846. BEGIN {
  847. # INITIALIZATION CODE
  848. }
  849.  
  850. # DEFINE PERL PACKAGE
  851. sub package_subroutine {
  852. print "Hello from Perl Package.\n";
  853. }
  854. # TO INDICATE THAT PACKAGE LOADS OK
  855. return 1;
  856.  
  857. END {
  858. # CLEAN UP CODE
  859. }
  860. With the following script we can call package subroutine "package_subroutine": test_package.pl
  861. #!/usr/bin/perl
  862.  
  863. use perl_package;
  864.  
  865. perl_package::package_subroutine();
  866.  
  867. 14. Databases connections
  868.  
  869. 14.1. Perl MySQL database connection
  870.  
  871. #!/usr/bin/perl
  872. #
  873. use Mysql;
  874.  
  875. $mysql_host = "perl_box";
  876. $mysql_database = "perl_connect";
  877. $mysql_user = "perl_programmer";
  878. $mysql_password = "perl";
  879.  
  880. $perl_mysql_connect = Mysql->connect($mysql_host, $mysql_database,
  881. $mysql_user, $mysql_password);
  882.  
  883. if ($perl_mysql_connect) {
  884. print "Perl have created connection to MySQL database!\n"
  885. } else {
  886. print "Perl could not create connection to MySQL database!\n"
  887. }
  888. 14.2. Perl PostgreSQL database connection
  889.  
  890. #!/usr/bin/perl
  891.  
  892. #load perl postgresql module
  893. use DBI;
  894.  
  895. $postgresql_database=perl_connect;
  896. $postgresql_user=perl_programmer;
  897. $postgresql_password=perl;
  898. $postgresql_host=perl_box;
  899.  
  900. # connect to perl to postgresql database
  901. my $perl_postgresql =
  902. DBI->connect("DBI:Pg:dbname=$postgresql_database;host=$postgresql_host",
  903. "$postgresql_user", "$postgresql_password");
  904.  
  905. if($perl_postgresql) {
  906. print "Perl established connection to PostgreSQL database\n";
  907. }
  908. 15. Object Oriented Perl
  909.  
  910. There are many materials focussed on object oriented Perl from the introductory PerlBoot to the more comprehensive PerlToot. In this section are topics or viewpoints which couldn't be found elsewhere.
  911. 15.1. Template of get/set methods
  912.  
  913. Below is an example of a script using an object with two pieces of data with a method to set/get each one: varName and varAge.
  914. linuxconfig:~/learn_perl/oo$ $ cat test.pl
  915. #!/usr/bin/perl
  916. use strict;
  917. use warnings;
  918. use Person;
  919.  
  920. my $p = Person->new();
  921.  
  922. $p->varName('Anna');
  923. $p->varAge(30);
  924.  
  925. print $p->varName." is ".$p->varAge." years old.\n";
  926. Running this function behaves as expected:
  927. linuxconfig:~/learn_perl/oo$ ./test.pl
  928. Anna is 30 years old.
  929. The obvious implementation of this object would be as follows:
  930. linuxconfig:~/learn_perl/oo$ cat Person.pm
  931. package Person;
  932.  
  933. use strict;
  934. use warnings;
  935.  
  936. sub new
  937. {
  938. my $class = shift;
  939.  
  940. my $self = {}; bless($self, $class);
  941. return $self;
  942. }
  943.  
  944. sub varName
  945. {
  946. my ($self, $name) = @_;
  947. if (defined($name)) {
  948. $self->{NAME} = $name;
  949. }
  950. return $self->{NAME};
  951. };
  952.  
  953. sub varAge
  954. {
  955. my ($self, $age) = @_;
  956. if (defined($age)) {
  957. $self->{AGE} = $age;
  958. }
  959. return $self->{AGE};
  960. };
  961.  
  962. 1;
  963. The main thing to observe in the code above is that the varName and varAge are identical in functionality. In the example below, we implement both of these methods using a single function template.
  964. linuxconfig:~/learn_perl/oo$ cat Person.pm
  965. package Person;
  966.  
  967. use strict;
  968. use warnings;
  969.  
  970. sub new
  971. {
  972. my $class = shift;
  973.  
  974. my $self = {}; bless($self, $class);
  975. return $self;
  976. }
  977.  
  978. my @vars = qw(Name Age);
  979. foreach my $var (@vars) {
  980. no strict 'refs'; # permit the symbolic references to varName, varAge
  981. *{"var".$var} =
  982. sub
  983. {
  984. my ($self, $stuff) = @_;
  985. if (defined($stuff)) {
  986. $self->{uc($var)} = $stuff; # change Name to NAME
  987. }
  988. return $self->{uc($var)};
  989. };
  990. }
  991.  
  992. 1;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement