For Programmers: Free Programming Magazines  


Home > Archive > PERL Beginners > March 2008 > special chars as scalar inside regex









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author special chars as scalar inside regex
Rob Benton

2008-03-28, 4:13 am


I've got a problem I think there may be a straight-forward solution to
that I just don't know. I have a program that reads a variable-length
input file. And the field delimiter of that file is given as an
argument. The problem is something like pipe "|" might show up as the
delimiter. So is there a way to quote/protect that in the split()
function without it being interpreted as a regex special character?

Something like:

../myprog.pl "|"

myprog.pl:
---------
my $delimiter = $ARGV[0];
my @fields = split(/$delimiter/, $line);


This is a very simplified example. Hope that makes sense.
Gunnar Hjalmarsson

2008-03-28, 4:13 am

Rob Benton wrote:
> I've got a problem I think there may be a straight-forward solution to
> that I just don't know. I have a program that reads a variable-length
> input file. And the field delimiter of that file is given as an
> argument. The problem is something like pipe "|" might show up as the
> delimiter. So is there a way to quote/protect that in the split()
> function without it being interpreted as a regex special character?
>
> Something like:
>
> ./myprog.pl "|"
>
> myprog.pl:
> ---------
> my $delimiter = $ARGV[0];
> my @fields = split(/$delimiter/, $line);


That's a FAQ.

perldoc -q "How can I quote a variable to use in a regex?"

--
Gunnar Hjalmarsson
Email: http://www.gunnar.cc/cgi-bin/contact.pl
John W. Krahn

2008-03-28, 4:13 am

Rob Benton wrote:
>
> I've got a problem I think there may be a straight-forward solution to
> that I just don't know. I have a program that reads a variable-length
> input file. And the field delimiter of that file is given as an
> argument. The problem is something like pipe "|" might show up as the
> delimiter. So is there a way to quote/protect that in the split()
> function without it being interpreted as a regex special character?
>
> Something like:
>
> ./myprog.pl "|"
>
> myprog.pl:
> ---------
> my $delimiter = $ARGV[0];
> my @fields = split(/$delimiter/, $line);
>
>
> This is a very simplified example. Hope that makes sense.


perldoc -f quotemeta

my @fields = split /\Q$delimiter\E/, $line;




John
--
Perl isn't a toolbox, but a small machine shop where you
can special-order certain sorts of tools at low cost and
in short order. -- Larry Wall
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com