Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl read file and split into variables issue

Tags:

perl

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?

like image 585
bsteo Avatar asked Dec 28 '25 10:12

bsteo


1 Answers

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

split /\|/, $line;
like image 143
ikegami Avatar answered Dec 31 '25 00:12

ikegami