Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: How to get split $var to work like split ' '?

by Eily (Monsignor)
on Sep 10, 2013 at 19:25 UTC ( [id://1053342]=note: print w/replies, xml ) Need Help??


in reply to How to get split $var to work like split ' '?

There's always the eval solution.

my $sep = ' '; $, = ', '; $\ = $/; my $string = " Hello World"; print split ' ', $string; print split $sep, $string; # This does not work print eval qq< split '$sep', \$string >;
Hello, World , , , , , , , , , , Hello, World Hello, World
This could do the trick as long as you don't try to use regexes. And maybe escaping the quotes in $sep would be a good idea too :P

Replies are listed 'Best First'.
Re^2: How to get split $var to work like split ' '?
by QM (Parson) on Sep 11, 2013 at 08:12 UTC
    Yes, that occurred to me later.

    Still, to follow the Principle of Least Astonishment, I'd like to be able to specify a regex. To avoid further if then's, I'd probably set the default like so:

    my $sep = q/' '/; $sep = shift @ARGV if @ARGV; # you get the idea my $line = " one two three \n"; my @words = eval qq(split $sep, \$line);

    Then something evaluating to a regex must be used, such as:

    $sep = q(/\s+/); $sep = q(//); $sep = q(/two|\s+/); $sep = q(m|/|);

    But the delimiters must be part of the string.

    (I'm ignoring for now the security issue of letting the user specify a regex, as this is a script just for me. And I'm not up to untainting the full regex language, so I can't see letting this into the wild hands of colleagues.)

    -QM
    --
    Quantum Mechanics: The dreams stuff is made of

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1053342]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (6)
As of 2024-04-18 12:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found