On Tue, Jun 2, 2009 at 17:29, Tony Esposito <tony1234567...@yahoo.co.uk> wrote:
> When trying to use split() where the delimiter is passed from the 
> command-line ( as seen in stub code that follows ),
> the code fails to parse/split input file via some characters (e.g. | ) but it 
> runs ok for others (e.g. , ).
>
> Any idea what could be causing this?
>
>
> Code:
> --------
>
>   use vars qw/ %opt /;
>   use Getopt::Std;
>   my $optString = 'd:';
>
>   getopts( "$optString", \%opt );
>
>   while(<FILE>) {
>     @cfgData = split(/$opt{d}/);
>     ...
>   }
snip

If the user passes in \| on the commandline, then your regex is /|/
which matches the nothing between characters.  The solution is to use
\Q and \E to tell the regex that the characters in $opt{d} are to be
treated as normal characters:

#!/usr/bin/perl

use strict;
use warnings;

use Getopt::Std;

our %opt;
getopts("d:" => \%opt);

die "usage: $0 -d delimiter\n" unless exists $opt{d};

while(<DATA>) {
        chomp;
        my @cfgData = split(/\Q$opt{d}\E/);
        print join(",", @cfgData), "\n";
}

__DATA__
a|b|c|d
e|f|g|h


-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to