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

Hi Perl Monks,

I am a beginner in perl programming. Can you help me to sort out a simple problem in perl script writing? I have used a map function in the middle of a program i.e.

say $_ for map {sprintf (“%d”, length)} split/$motif/, $string;

It works nicely in command prompt in Windows XP and shows the results correctly. But I want the results of this line (e.g. 0 6 7 8 4 etc. ) printed in a .txt or .docx page as output. So, I need to assign the result of this code to a variable like $a or @a for use in print command like print ”$a or @a”;.

I searched for references in Google but those references have not worked in my program. I shall appreciate if any perl monk can help me sort out this problem by assigning a suitable variable to the output of this code to get the result as print ”$a or @a “; in my program.

  • Comment on Request to sort out a problem in perl program for getting result as print "@a or $a" of a map function code
  • Select or Download Code

Replies are listed 'Best First'.
Re: Request to sort out a problem in perl program for getting result as print "@a or $a" of a map function code
by jwkrahn (Abbot) on Jan 23, 2012 at 08:58 UTC
    say $_ for map {sprintf (“%d”, length)} split/$motif/, $string;

    You don't really need map there, you could just do:

    say length for split /$motif/, $string;

    And to store that in an array you would need map:

    my @a = map length, split /$motif/, $string;
Re: Request to sort out a problem in perl program for getting result as print "@a or $a" of a map function code
by ikegami (Patriarch) on Jan 23, 2012 at 09:33 UTC
    The only difference between printing to the STDOUT and print to a file is you provide a handle to say or print. So that means
    say $fh length for split $motif, $string;
    simply changes to
    open(my $fh, '>', $qfn) or die("Can't create \"$qfn\": $!\n"); say $fh length for split $motif, $string;

    No need to involve a variable, which would be done as follows:

    my @lengths = map length, split $motif, $string;
Re: Request to sort out a problem in perl program for getting result as print "@a or $a" of a map function code
by kielstirling (Scribe) on Jan 23, 2012 at 09:46 UTC

    The following is a working example. Have fun !!

    -Kiel R Stirling.
    #!/usr/bin/perl -w use strict; use IO::File; my $string = "1 2 3 4 5 6 7 8"; my $fh = IO::File->new(">/tmp/output.txt"); die "Failed to open output file $!" unless defined $fh; say $fh $_ for split /\s/, $string; $fh->close;