in reply to printing array using map

Is there a reason you insist on using 'map'? An explicit 'for' loop would be more legible. Not that I dislike 'map', but once past a certain degree of complexity, you really should break it out.

#!/usr/bin/perl -wl use strict; print for map { y/[]//d; join " ", reverse split } <DATA>; __DATA__ w1 w2 w3 [t4 w4] w5

Update: My assumption is the opposite of netwallah's, since 'map' would print an arrayref as 'ARRAY(0xDEADBEEF)' rather than '[foo bar]'.


-- 
Human history becomes more and more a race between education and catastrophe. -- HG Wells

Replies are listed 'Best First'.
Re^2: printing array using map
by Anonymous Monk on Apr 27, 2008 at 18:26 UTC
    Actually lets make this more clear, let's say I have an text file like this :
    w1 w2 w3 [t4 w4] w5 w6
    and I want to process it to have something like this in output :
    w1 w2 w3 w4 t4 w5 w6
    each w is a token and t is a lable for some tokens. I've tried this but it dosnt work and I get the same output.
    use strict; my $file = $ARGV[0]; open IN, $file or die "Can't open"; my @file =<IN>; close IN; m/\[(\S+)\s(\S+)\]/ ? print qq[$2 $1\n] :print qq[$_] for @file;
    while my file is a text with my data as below.
    w1 w2 w3 [t4 w4] w5 w6
      Firstly, using the readline operator with no filehandle defaults to opening and reading the files supplied as command-line arguments so you don't need to open the filehandle yourself. Secondly, you can use just one capture in the regex by using a negated character class, in other words capture zero or more non closing square brackets.

      use strict; use warnings; print map { chomp; s{^\[([^\]]*)\]}{$1}; qq{$_\n}; } <>;

      Running it gives

      J:\johngg\Scripts\Monks>type spw683152.dat w1 w2 w3 [t4 w4] w5 w6 J:\johngg\Scripts\Monks>perl spw683152 spw683152.dat w1 w2 w3 t4 w4 w5 w6

      I hope this is useful.

      Cheers,

      JohnGG

        Why chomp when you put the newline back anyway? If the OP doesn't need to explicitly check for balanced brackets then the regex simplifies too:

        print map {s/\[|\]//g; $_} <>;

        Or if your taste runs to for loops and you don't mind the occasional comma operator:

        s/\[|\]//g, print for <>;

        Perl is environmentally friendly - it saves trees
        My understanding is that the OP wants the "[t4 w4]" input reversed on output: "w4 t4"

        Update: Gah. Corrected brackets. Thanks kyle


        Unless I state otherwise, my code all runs with strict and warnings
      In what way does oko1's solution not work for you?

      Using your input of:

      w1 w2 w3 [t4 w4] w5

      produces:

      w1 w2 w3 w4 t4 w5

      using an elegance I'd be proud of. Is that not what you're after?


      Unless I state otherwise, my code all runs with strict and warnings