Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

split and join

by root (Scribe)
on Nov 12, 1999 at 02:46 UTC ( #970=perltutorial: print w/ replies, xml ) Need Help??

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 +e characters #@simpsons now containts ("Bart","Lisa","Maggie","Marge","Homer");

Suppose we had a list of records of the form
Name|Phone Number|Address
We could open a file while which contained those records and do something like this:
open FILE, "data.txt"; while(<FILE>) chomp; ($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 +properly 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"; } close FILE;

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) or join($glue,$var1,$var2....) The glue is simply the string that goes between two strings to hold them together. Here are a few examples:
$string=join(" ",@simpsons); #string now equals "Bart Lisa Maggie Marge Homer"; $name="Bob"; $phone="555-5555"; $address="42 Tulip Lane, Holland MI, 49423"; $string=join("|",$name,$phone,$address); #$string is now equal to "Bob|555-5555|42 Tulip Lane, Holland MI, 4942 +3"

Comment on split and join
Select or Download Code
RE: split and join
by Anonymous Monk on May 10, 2000 at 23:36 UTC
    I have a question...not really pertaining to the subject at hand, but it is bugging me nonetheless. How come there isn't a link back to the main contents table for this tutorial from here, and if there is (and I am missing something) how come it is difficult to find?
      What about the link to Tutorials in the information nodelet on the right?
Re: split and join
by jeroenes (Priest) on Jan 08, 2001 at 18:46 UTC
    You may find supersplit useful as well. It does split/join at multiple levels, so uses multi-dimensional arrays. For example
    open FILE, "data.txt" $array=supersplit('|', \*FILE );
    Would result in one array containing all lines as rows and the separate items as columns. The first item for example, can be accessed by $array->[0][0]. See POD of the script for more examples and doc.

    Jeroen
    I was dreaming of guitarnotes that would irritate an executive kind of guy (FZ)

Error in the example code
by Anonymous Monk on Sep 10, 2001 at 05:39 UTC
    Hello all,

    I just thought I'd let you know there is an error in this example code.

    @simpsons=split(/\s+/ $line); #now splits $line on 1 or more whitespac +e characters #@simpsons now containts ("Bart","Lisa","Maggie","Marge","Homer");

    You are missing a comma (/\s+/,$line). On a seperate note does anyone know how I would join an array with a comman except for the last value.

    ie I have an array of postcodes, that I am going to print out as a string.

    $postcodes=join(", ",@Postcode_array); print "any area. postcode1, postcode2, postcode3\n"; What I would like to print out is this. print "any area. postcode1, postcode2 & postcode3\n";

    Any help would be great... Thanks, Greg

    Edit: g0n - code tags & formatting

      first store the length of array by using count variable and then exclude the last element of array... is this a good idea...?
      my @arr = (1 .. 10); print join(', ', @arr[0 .. $#arr - 1]), " & $arr[$#arr]\n";
      --
      <http://www.dave.org.uk>

      "The first rule of Perl club is you don't talk about Perl club."

Re: split and join
by Anonymous Monk on Dec 18, 2001 at 07:11 UTC
    using the chomp and split functions is fine for splitting records with 3 fields, but supposing you had 100 fields and you only wanted the 55th and 80th field values. there would be no real point in extracting all field values. Is there not a way to search/locate the nth delimeter ("|") and then extract the field directly following?
Re: split and join
by Anonymous Monk on Jan 04, 2002 at 03:52 UTC
    just wondering if u had

    $line="Bart Lisa Maggie Marge Homer blah blah"; @simpsons=split(/\s+/, $line);

    what i wanted is to split so as to get

    @simpsons = {"Bart", "Lisa", "Maggie", "Marge", "Homer blah blah"}

    notice the last part i want it all attached. Assume i dont know how many "blah"s follow after "Homer".

    Edit: g0n - code tags & formatting

      Simple. Use a counter to find the numbers of the Caps in the string and then do..while op until you reach that number.
Re: split and join
by Anonymous Monk on Apr 22, 2002 at 22:38 UTC
    what if you need to split by the plus character "+" the compiler keeps on chucking a spazz. is there anyway to get around this?? simon.hilton@sun.com

      '+' is a metacharacter which has meaning in regular expressions. To match a literal plus, you need to escape ('backwhack') it.

      split /\+/;

      After Compline,
      Zaxo

      split takes a pattern (more or less a regular expression, though there are special cases you might want to read up on), not a static string to separate chunks in the input string, and it happens that the '+' character is special, so you just need to escape it like so:
      @array = split '\+', 'abc+def'; print "@array";
      gives abc def
      By the way, you might want to provide the actual error message in future if you need assistance, as "chucking a spazz" covers a lot of bases!

      --
      I'd like to be able to assign to an luser

Re: split and join
by nobettername (Initiate) on Nov 10, 2005 at 08:06 UTC
    Hi, Can anyone tell me how to split the data {"0.7591.4166.6352.6465.4574.1653.833"} into {"0.759","1.416","6.635","2.646","5.457","4.165","3.833"} Thanks in advance.
      $data = "0.7591.4166.6352.6465.4574.1653.833"; @data = $data =~ /\d\.\d\d\d/g;

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perltutorial [id://970]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (10)
As of 2014-09-17 16:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (91 votes), past polls