Home arrow Perl Programming arrow Page 3 - Perl Lists: The Split() Function

Limiting the Amount of Splits - Perl

In this fourth part of our series on Lists, we will start off with the split() function and hopefully end by covering hashes. In our last article, we covered the splice() function, which we used to add, remove, and replace elements in a list. We then used it to create variables and arrays. We also worked with some operators to repeat a list and to create sequential lists.

  1. Perl Lists: The Split() Function
  2. Using Split() On a String
  3. Limiting the Amount of Splits
  4. Assigning a List to Another List
By: James Payne
Rating: starstarstarstarstar / 6
April 07, 2008

print this article



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:


$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:




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:


$Some = "Hamburger Pork Chicken Fish";

($Meat, $Pork, $Poultry, $Fish) =


print $Meat . "\n";

print $Pork . "\n";

print $Poultry . "\n";

print $Fish . "\n";

The result is:





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.

>>> More Perl Programming Articles          >>> More By James Payne

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Perl Turns 25
- Lists and Arguments in Perl
- Variables and Arguments in Perl
- Understanding Scope and Packages in Perl
- Arguments and Return Values in Perl
- Invoking Perl Subroutines and Functions
- Subroutines and Functions in Perl
- Perl Basics: Writing and Debugging Programs
- Structure and Statements in Perl
- First Steps in Perl
- Completing Regular Expression Basics
- Modifiers, Boundaries, and Regular Expressio...
- Quantifiers and Other Regular Expression Bas...
- Parsing and Regular Expression Basics
- Hash Functions

Developer Shed Affiliates


Dev Shed Tutorial Topics: