Perl recipies - PowerPoint PPT Presentation

1 / 26
About This Presentation
Title:

Perl recipies

Description:

Use reverse to create an inverted hash whose values are the original hash's keys ... LOOKUP maps keys to values %REVERSE = reverse %LOOKUP; Sorting a hash ... – PowerPoint PPT presentation

Number of Views:113
Avg rating:3.0/5.0
Slides: 27
Provided by: sangb
Category:

less

Transcript and Presenter's Notes

Title: Perl recipies


1
Perl recipies
  • Problem
  • You want to print out the number represented by a
    given ASCII character, or you want to print out
    an ASCII character given a number.
  • Solution
  • Use ord to convert a character to a number, or
    use chr to convert a number to a character

2
  • num ord(char) char chr(num) The c
    format used in printf and sprintf also converts a
    number to a character
  • char sprintf("c", num) slower than
    chr(num)
  • printf("Number d is character c\n", num,
    num)
  • Number 101 is character e
  • A C template used with pack and unpack can
    quickly convert many characters.
  • _at_ASCII unpack("C", string)
  • STRING pack("C", _at_ascii)

3
Case controlling
  • use locale
  • big uc(little)
  • little lc(big)
  • big \Ulittle
  • little \Lbig
  • \u, \l - just one character

4
  • 1.12. Reformatting Paragraphs
  • Problem
  • Your string is too big to fit the screen, and you
    want to break it up into lines of words, without
    splitting a word between lines. For instance, a
    style correction script might read a text file a
    paragraph at a time, replacing bad phrases with
    good ones. Replacing a phrase like utilizes the
    inherent functionality of with uses will change
    the length of lines, so it must somehow reformat
    the paragraphs when they're output.
  • Solution
  • Use the standard TextWrap module to put line
    breaks at the right place.

5
  • use TextWrap
  • _at_OUTPUT wrap(LEADTAB, NEXTTAB, _at_PARA)
  • LEADTAB is the tab for the 1st line and
  • NEXTTAB is the tab for the subsequent lines

6
  • You want to check whether a string represents a
    valid number. This is a common problem when
    validating input, as in a CGI script.
  • Solution
  • Compare it against a regular expression that
    matches the kinds of numbers you're interested
    in.
  • if (string /PATTERN/) is a number else
    is not

7
  • warn "has nondigits" if /\D/
  • warn "not a natural number" unless /\d/
    rejects -3
  • warn "not an integer" unless /-?\d/
    rejects 3
  • warn "not an integer" unless /-?\d/
  • warn "not a decimal number" unless
    /-?\d\.?\d/ rejects .2
  • warn "not a decimal number" unless
    /-?(?\d(?\.\d)?\.\d)/
  • warn "not a C float" unless /(-?)(?\d\.\d)\d
    (\.\d)?(Ee(-?\d))?/

8
Operating on a series of integers
  • foreach (X .. Y) _ is set to every integer
    from X to Y, inclusive
  • foreach i (X .. Y) i is set to every
    integer from X to Y, inclusive
  • for (i X i every integer from X to Y, inclusive

9
Arabic and Roman numeral
  • use Roman
  • roman roman(arabic) convert to roman
    numerals
  • arabic arabic(roman) if isroman(roman)
    convert from roman numerals

10
Random number
  • Problem
  • You want to make random numbers in a given range,
    inclusive, from x to Y.
  • Solution
  • Use Perl's rand function.
  • random int( rand( Y-X1 ) ) X

11
Multiplying matrices
  • Problem
  • You want to multiply a pair of two-dimensional
    arrays. Mathematicians and engineers often need
    this.
  • Solution
  • Use the PDL modules, available from CPAN. PDL is
    the Perl Data Language  - modules that give fast
    access to compact matrix and mathematical
    functions

12
Example)
  • use PDL
  • a pdl 3, 2, 3 , 5, 9, 8 ,
  • b pdl 4, 7 , 9, 3 , 8, 1 ,
  • c a x b x overload

13
Perl grep function
  • Ex) _at_matching grep /gnat / who
  • Ex) _at_persons grep _-income 26000
    _-income
  • Unlike unix grep function, perl grep function
    can have test conditions inside the bracket.

14
Testing for the Presence of a Key in a Hash
  • Problem
  • You need to know whether a hash has a particular
    key, regardless of any possible associated value.
  • Solution
  • Use the exists function.

15
exists functions
  • does HASH have a value for KEY ?
  • if (exists(HASHKEY)) it exists else
    it doesn't

16
Retrieving from a Hash in Insertion Order
  • Problem
  • The keys and each functions give you the hash
    elements in a strange order, and you want them in
    the order in which you inserted them.
  • Solution
  • Use the TieIxHash module.

17
Example)
  • use TieIxHash
  • tie HASH, "TieIxHash" manipulate HASH
  • _at_keys keys HASH _at_keys is in insertion
    order

18
Inverting a hash
  • Problem
  • Hashes map keys to values. You have a hash and a
    value for which you want to find the
    corresponding key.
  • Solution
  • Use reverse to create an inverted hash whose
    values are the original hash's keys and vice
    versa.
  • LOOKUP maps keys to values
  • REVERSE reverse LOOKUP

19
Sorting a hash
  • The following code simply uses sort to order the
    keys alphabetically
  • foreach food (sort keys food_color) print
    "food is food_colorfood.\n"
  • This sorts the keys by their associated values
  • foreach food (sort food_colora cmp
    food_colorb keys food_color) print
    "food is food_colorfood.\n"

20
  • This sorts by length of the values
  • _at_foods sort length(food_colora)
    length(food_colorb) keys food_color
    foreach food (_at_foods) print "food is
    food_colorfood.\n"

21
Presizing a Hash
  • Problem
  • You want to preallocate memory for a hash to
    speed up your program so Perl won't have to
    incrementally allocate memory each time a new
    entry is added to the hash.
  • Solution
  • Assign the number of key-value pairs your hash
    will have to keys HASH.
  • presize hash to num
  • keys(hash) num
  • keys(users) 512

22
Representing Relationships Between Data
  • Problem
  • You want to represent relationships between
    elements of data - for instance, the mother of
    relationship in a family tree or parent process
    for a process table.
  • Solution
  • Use a hash to represent the relationship.

23
Example) part of the family tree from the Bible
  • father ( 'Cain' 'Adam',
  • 'Abel' 'Adam',
  • 'Seth' 'Adam',
  • 'Enoch' 'Cain',
  • 'Irad' 'Enoch',
  • 'Mehujael' 'Irad',
  • 'Methusael' 'Mehujael',
  • 'Lamech' 'Methusael',
  • 'Jabal' 'Lamech')

24
Example)
  • This lets us, for instance, easily trace a
    person's lineage
  • while () chomp
  • do print "_ " print the current name
  • _ father_ set _ to _'s father
    while defined until we run out of fathers
    print "\n"

25
Whom did Lamech beget?"
  • while ( (k,v) each father ) push( _at_
    childrenv , k )
  • " ', ' separate output with commas
  • while () chomp
  • if (children_) _at_children
    _at_children_ else _at_children "nobody"
  • print "_ begat _at_children.\n"

26
Copying and Substituting Simultaneously
  • Problem
  • You're tired of constantly using two separate
    statements with redundant information, one to
    copy and another to substitute.
  • Solution
  • Instead of
  • dst src dst s/this/that/
  • use
  • (dst src) s/this/that/
Write a Comment
User Comments (0)
About PowerShow.com