2

Must look dumb, but I have a little Perl code to read a file with contents like this:

John|Doe
John|Smith
No|Name
Ozzy|Osbourne

I want to read the file and get the data as variables $firstname $lastname:

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

open(DB, "$ARGV[0]") || die ":: Can't open database.\n";

my $line;

foreach $line (<DB>){
  chomp $line;
  $line =~ s/^\s+//;
  $line =~ s/\s+$//;
  my ($firstname, $lastname) = split /|/, $line;
  print "Firstname: $firstname - Lastname: $lastname\n";
}

What I get is:

Firstname: J - Lastname: o
Firstname: J - Lastname: o
Firstname: N - Lastname: o
Firstname: O - Lastname: z

First and second characters. Where am I wrong?

1
  • same result, tried also "|" Commented Mar 11, 2014 at 14:09

2 Answers 2

9

Split takes a regular expression. If you want to match | literally, you need to escape it.

split /\|/, $line;
Sign up to request clarification or add additional context in comments.

1 Comment

did not know that, gotta love perl
0

You can do it without using split, with regex

open(FH,test.txt);
my @array=<FH>;

foreach(@array)
{
$_=~ m/(\w+)\|(\w+)/;
print "Firstname: $1 ,Lastname: $2 \n";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.