in reply to Re: printing array using map
in thread printing array using map

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

Replies are listed 'Best First'.
Re^3: printing array using map
by johngg (Canon) on Apr 27, 2008 at 20:53 UTC
    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
        Yep, no need to chomp, force of habit I guess :-(

        Cheers,

        JohnGG

      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
        Oh dear! I must have been sleepwalking when I posted as I completely missed that requirement. Too late, I dimly remember the advice teachers tried to drum into us before exams, "Read the questions carefully" ;-/

        Cheers,

        JohnGG

Re^3: printing array using map
by FunkyMonk (Bishop) on Apr 27, 2008 at 22:19 UTC
    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