http://qs1969.pair.com?node_id=726739


in reply to Re^3: variable mystery
in thread variable mystery

Thanks, I guess that's another syntax check I didn't learn.

Hi again Oko1, your suggested code has a different syntax, especially the addition of the '1' arg, can you tell me what it does? Thanks.

my @fields = grep { s/^\s+|\s+$//g; 1; } split /\|/;

Replies are listed 'Best First'.
Re^5: variable mystery
by parv (Vicar) on Nov 29, 2008 at 07:59 UTC

    In oko1's modification, grep is being used for side effects. grep returns the values of the list (in this case split result) for which the expression is true (in this case it is 1 for any and every input). Substitutions as a side effect just happen to be before forcing the test to be true.

    Do modify your code if you are using perl 5.8.7. Either use an explicit loop variable other than $_ ($in should have worked in you had supplied it to split instead of $_; related code is missing)...

    for my $in ( <$fh> ) { my @p = map { ... } split /\|/ , $in; ... }

    ... or just omit it ...

    for ( <$fh> ) { my @p = map { ... } split /\|/ , $_; ... }

    As oko1 said that 1 is the return value of s/// on success; false or empty string on failure. Using a comma, you were generating a 2-element list of s/// return value & $_ (as the last expression of map). Unlike oko1's statement about returning empty $_, returning $_ works just fine ...

    print join ', ' , map { s/^\s+// ; s/\s+$// ; $_ ; } split /\|/ , 'p | q|r|s | t' ;

    In any case, there is no need of a map or a grep with side effects since split can take care of the spaces itself as it takes a regular expression to split on ...

    print join ', ' , split /\s*\|\s*/ , 'p | q|r|s | t' ;

    There are also Text::CSV* modules for your parsing needs.

    Back to your problem ...

    on line 12 in my script, I get nothing. I've found that any even-numbered element specified on line 12 gives me nothing, it's odd, I thought the 0th element would be 'Baw', the 1st element would be 'Vao' and so on.
    # input. Baw|Vao|111 Noa St||NewYork|NY|10012|2123456789|123456789
    # code. my @fields = (map { s/^\s+//; s/\s+$//, $_ } split /\|/, $_);

    So, after split, map produced ('', Baw) for Baw, ('', Vao) for Vao and so on. The array then would have an empty string at index 0, Baw at 1, empty string at 2, Vao at 3 and so on, so forth. Since you had used \r, you missed the empty strings.