cmv has asked for the wisdom of the Perl Monks concerning the following question:
I'm having difficulty figuring out how to get split to do its job with data that has initial spaces, when I need to set a limit.
Consider the following:
This works wonderfully (as stated in the Camel book), the initial spaces in the data are ignored and each call to split returned a list with two elements!use strict; use warnings; use Data::Dumper; my @data = ( " 56 1752.eps", " 56 2613.eps", " 56 3469.eps", " 8 INPUT000", " 16 INPUT001", " 16 INPUT002", " 96 MTA.1.ps", " 96 MTA.6.ps", " 80 MTA.7.ps", " 32 head.eps", " 8 labs", " 0 lib", " 8 mkexe.bat", " 112 out", " 0 screenshots", "8720 trace.exe", " 16 trace.pl", " 8 tracehosts", "1160 trace.041409.exe", "1160 trace.orig.exe", ); foreach (@data) { print STDERR Dumper(split), "\n"; } OUTPUT SAMPLE: $VAR1 = '56'; $VAR2 = '1752.eps'; $VAR1 = '56'; $VAR2 = '2613.eps'; $VAR1 = '56'; $VAR2 = '3469.eps';
Now, I would like to add a limit to the number of fields that split will split on. Notice the changes in the data below, and I still want each split to return a list with two elements:
Well, split is returning a list with two elements in every case, but in the case of the lines with initial spaces, it returns a null for the first element.use strict; use warnings; use Data::Dumper; my @data = ( " 56 1752.eps a b", " 56 2613.eps", " 56 3469.eps", " 8 INPUT000 a b", " 16 INPUT001", " 16 INPUT002", " 96 MTA.ps", " 96 MTA.6.ps a b", " 80 MTA.7.ps", " 32 head.eps", " 8 labs", " 0 lib a b", " 8 mkexe.bat", " 112 out", " 0 screenshots", "8720 trace.exe a b", " 16 trace.pl", " 8 tracehosts", "1160 trace.041409.exe a b", "1160 trace.orig.exe", ); foreach (@data) { print STDERR Dumper(split /\s+/, $_, 2), "\n"; } OUTPUT SAMPLE: $VAR1 = ''; $VAR2 = '56 1752.eps a b'; $VAR1 = ''; $VAR2 = '56 2613.eps'; $VAR1 = ''; $VAR2 = '56 3469.eps';
How can I get the second case to ignore leading spaces like the first case did?
Many thanks...
-Craig
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Split(), Initial Spaces, & a limit?
by ikegami (Patriarch) on Jul 20, 2010 at 16:03 UTC | |
|
Re: Split(), Initial Spaces, & a limit?
by jethro (Monsignor) on Jul 20, 2010 at 15:57 UTC | |
|
Re: Split(), Initial Spaces, & a limit?
by Anonymous Monk on Jul 20, 2010 at 15:54 UTC | |
|
Bug in Sort::Fields?
by cmv (Chaplain) on Jul 20, 2010 at 17:08 UTC | |
by ikegami (Patriarch) on Jul 20, 2010 at 17:29 UTC | |
by cmv (Chaplain) on Jul 20, 2010 at 18:39 UTC | |
by ikegami (Patriarch) on Jul 20, 2010 at 19:02 UTC | |
by cmv (Chaplain) on Jul 20, 2010 at 19:14 UTC | |
| |
by ikegami (Patriarch) on Jul 20, 2010 at 19:32 UTC | |
by cmv (Chaplain) on Jul 20, 2010 at 20:07 UTC |