Perl Programming Page 3 - Perl Lists: The Split() Function |
Sometimes you might not wish to split the entire string. Say you just want the first two delimited results, and not all of them. Here is how you would get those results: #!/usr/bin/perl $Some = "Hamburger--Fries--Tofu--Banana"; @Yum = split(/--/,$Some,3); print @Yum[0] . "\n"; print @Yum[1] . "\n"; print @Yum[2] . "\n"; In this example, the result is: Hamburger Fries Tofu--Banana What happens here is that the function splits the first and second words and puts them into the first and second ([0] and [1]) positions in the @Yum array. It then stops seeking the delimiter and places whatever is left over into the third position of our array. That is why Tofu and Banana are still together, and indeed, even have their delimiter as well. We can also use this method to assign values to a group of variables. Let's say we have a string that lists several types of meat and we want each type of meat in its own variable. Here is how we would achieve this: #!/usr/bin/perl $Some = "Hamburger Pork Chicken Fish"; ($Meat, $Pork, $Poultry, $Fish) = split(/t/,$Some,4); print $Meat . "\n"; print $Pork . "\n"; print $Poultry . "\n"; print $Fish . "\n"; The result is: Hamburger Pork Chicken Fish You may have noticed something bizarre in the code where we usually place our delimiter. There is still a delimiter here; we are simply delimiting by the special character t, or tab. You can also use split() on text files, but we will save that for a future tutorial.
blog comments powered by Disqus |
|
|
|
|
|
|
|