Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

String processing

by dovah (Novice)
on Jul 31, 2014 at 11:05 UTC ( [id://1095723]=perlquestion: print w/replies, xml ) Need Help??

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

Hi! I'd like to ask for help because my code isn't behaving correctly (and I can't figure out why). So, here's my issue. I have to deduce positions in a "simple string" given positions in a "complete string". Here's a minimal exemple of my input file:
#name complete(cs) len(cs) simple(ss) len(ss) pos(cs) NAME1 A0AAA000AAA00A 14 AAAAAAAA 8 4,6 NAME2 AAAA0AA00000A 13 AAAAAAA 7 7
Here's my code:
$ perl -anle ' print "$_ position(cs)" and next if /^#/; printf "%s",$_; for $pos_ss (split ",",$F[5]) { $char = substr($F[1],$pos_ss-1,1); @cs = split //,$F[3]; @cs_idx = grep {$cs[$_] eq $char} 0..$#cs; push @res,++$cs_idx[$pos_ss-1]; } printf "%14s\n", join ",",@res; @res=(); ' file
And here's my expected output:
NAME1 A0AAA000AAA00A 14 AAAAAAAA 8 4,9 3,5 NAME2 AAAA0AA00000A 13 AAAAAAA 7 7 6
In the provided exemple, I have to say that the 4th character (which is the 3rd "A") in the complete string(cs) corresponds to the the 3rd character in the simple string(ss), and so on... Could you please help me formatting/reviewing my code? Thanks in advance for your precious help!!

Replies are listed 'Best First'.
Re: String processing
by Anonymous Monk on Jul 31, 2014 at 12:29 UTC

    Solved with a long-liner:

    perl -aple '$" = ","; my $rx = join "", map qq((\Q$_\E)?), split //, $ +F[1]; chomp; $_ .= " @{[map $_+1, @-[split /,/, $F[5]]]}" if $F[3] = +~ $rx;'

      Ahem, using @+ saves some strokes:

      perl -aple '$" = ","; my $rx = join "", map qq((\Q$_\E)?), split //, $ +F[1]; chomp; $_ .= " @{[@+[split /,/, $F[5]]]}" if $F[3] =~ $rx;'

Re: String processing
by Anonymous Monk on Jul 31, 2014 at 15:48 UTC
    You can save some more (and still use printf):
    perl -lane '$F[3] =~ ($F[1] =~ s/./($&)?/gr) && printf "%-60s%s\n", $_, join ",", @+[eval "$F[5]"]'
    OP, I THINK we're trying to say that your code is difficult to read. I THINK there is a bug in your code, but I'm not sure. Write a real script, and you'll get better answers...
      Forgot the skipping comments part! :)
      perl -lane '/^#/ || $F[3]=~($F[1]=~s/./($&)?/gr) && printf "%-50s%s\n", $_, join ", ", @+[eval $F[5]]'

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1095723]
Approved by AppleFritter
Front-paged by toolic
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (3)
As of 2024-04-26 06:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found