Regular expressions can be used to break up strings. This is what split
does. The join
function on the other hand
takes a list of strings and combines them together again.
$line="Bart Lisa Maggie Marge Homer";
@simpsons=split(/\s/, $line); #splits $line and uses a piece of whites
+pace as a delimiter.
#@simpsons now contains ("Bart","","Lisa","Maggie","Marge","Homer");
#notice there is an extra space between Bart and Lisa so we get an emp
+ty element in the array there.
#lets try a better delimiter that will eliminate that from happening
@simpsons=split(/\s+/ $line); #now splits $line on 1 or more whitespac
#@simpsons now containts ("Bart","Lisa","Maggie","Marge","Homer");
Suppose we had a list of records of the form
We could open a file while which contained those records and do something like this:
open FILE, "data.txt";
($name,$phone,$address)=split(/\|/); #splits the default variable $
+_ on |
#notice we have to put \| sinc
+e | is a metacharacter
#that represents or. Otherwise
+ we'd be matching
#empty string or empty string
#then we place the results in
+variables instead of a list
#the parentheses around the va
+riable names need
#to be there for this to work
print "Name: $name\n"; #Now we print out the informat
+ion in a more readable form
print "Phone Number: $phone\n";
print "Address: $address\n\n";
The function join
can be used to reconstruct split up values into one string again.
The syntax for calling this function is join($glue, @array)
The glue is simply
the string that goes between two strings to hold them together.
Here are a few examples:
#string now equals "Bart Lisa Maggie Marge Homer";
$address="42 Tulip Lane, Holland MI, 49423";
#$string is now equal to "Bob|555-5555|42 Tulip Lane, Holland MI, 4942
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.
| & || & |
| < || < |
| > || > |
| [ || [ |
| ] || ] |