Ronnie has asked for the wisdom of the Perl Monks concerning the following question:

Hi again folks I perhaps (no perhaps about it!) phrased my last question badly! I'm trying to perform a split using \n as the split character. This works fine on scalars defined within my script unfortunately the field to be split comes via @ARGV as a parameter and that most definately doesn't work!
#!/usr/bin/perl -w # use strict ; # my $line = undef ; my @lines = () ; # my ($test) = @ARGV ; # #my $test = "x\ny\nz" ; print "\nTest :: $test\n" ; my @foo = split /\n/, $test; foreach $line (@foo) { print "\n$line\n" ; } # print "\n" ; #
This doesn't work regardless of whether the parameter is in single or double quotes or is not in fact quoted! I'm baffled does anyone have a solution to this? Thanks Ronnie

Replies are listed 'Best First'.
Re: Split/Parameter Problem
by jZed (Prior) on Jan 06, 2005 at 17:02 UTC
    Are you trying to split on newline or on the characters \n? If the later, you need to escape the backslash in your search. If the former, what OS and shell are you using and how do you pass in the data?
Re: Split/Parameter Problem
by legato (Monk) on Jan 06, 2005 at 19:15 UTC

    Depending on your OS, you may not have "\n" in your data at all: it might be "\r\f" (CR-LF) instead (or, rarely, something else). Try:

    my @foo = split "\n|\r\f", $test;
    Also, my ($test) = @ARGV will put only the first element of @ARGV (that is, $ARGV[0]) in $test. Is that what you wanted?

    To help debug what you've got, try this:

    $test =~ s/\n/**/g; ## replace all \n with '**' $test =~ s/\r/!!/g; ## replace all \r with '!!' print STDERR qq/'$test'/;
    If you still can't figure out what's wrong, paste the output from that, so maybe one of us will see something you're missing.

    Anima Legato
    .oO all things connect through the motion of the mind

      Or
      split(/\Q$RS\E/,$test);
      to split on the contents of Perl's current line seperator.
Re: Split/Parameter Problem
by mifflin (Curate) on Jan 06, 2005 at 16:57 UTC
    try single quoting your command line string
    # cat x use warnings; use strict ; for my $line (split /\\n/, shift) { print "$line\n" ; } for my $line (split /\n/, "x\ny\nz") { print "$line\n" ; } # perl x 'a\nb\nc' a b c x y z
A reply falls below the community's threshold of quality. You may see it by logging in.