Home > Perl, Programming > Read lines from a file and split by delimiter.

Read lines from a file and split by delimiter.

This reads a file line by line and then will split the lines based on the delimiter in this case a tab.

#!/usr/bin/perl
use strict;
use warnings;

## Open the file or exit with an error
open FILE, 'exampleFile.txt' or die $!;
## Make $line equal to one line in the file at a time until the end
foreach my $line (<FILE>)
{
    ## remove the newline from $line.
    chomp($line);
    
    ## Split the line with a regex (which is just the tab char)
    my @lineElements = split(/\t/, $line);
    
    ## Loop through the lineElements array and print each one
    foreach my $element (@lineElements)
    {
        print "$element\n";
    }
}
Advertisements
Categories: Perl, Programming
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: