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

So the problem is that i need to add leading zeros back to the numbers after i put them into an array. But the split function joins all the data into 1 long stream so i cant do that. It also means that typing more than 1 word can break the code. Sorry if the answer is simple i am self learning. For the file, you can make an array of 10 fruits, then for numbers an array using 1..10

use strict; use warnings; use JSON qw( decode_json); use File::Find; #Change This Root Depending On File Location open (MYFILE, "F:/Program Files (x86)/Spreadsheets/Words.txt") or die "Could not open required file $!"; my $firstText = do { local $/; <MYFILE> }; my @firstText = split(' ', $firstText); open (FILE, "F:/Program Files (x86)/Spreadsheets/Numbers.txt") or die "Could not open required file $!"; my $firstNumbers = do { local $/; <FILE> }; my @firstNumbers = split(' ', $firstNumbers); print "Text Enter\n"; my $sentance = <>; my @sentance = split(' ', $sentance); print @sentance; print $sentance; use List::MoreUtils qw(first_index); my @indexes; foreach my $place (sentance) { push (@indexes, first_index { $_ eq $place } @firstText); }; print @indexes;

Replies are listed 'Best First'.
Re: Seperating values with spaces in array
by Corion (Patriarch) on Jan 17, 2016 at 11:56 UTC

    In the case you want leading zeroes on the elements of @indexes, either put the leading zeroes on the elements before printing, or while printing them:

    ... push @indexes, sprintf '%03d', first_index { $_ eq $place } @first +Text; ...

    or

    print sprintf "%08d\n", $_ for @indexes;
      Thank you! this fixed it! I thought %06d would be the solution but i didnt know how to properly implement it. Thank you
        ... i didnt know how to properly implement it.

        Please see detailed discussion of printf and sprintf format specifiers in sprintf docs. (See also
            perldoc -f sprintf
        from the command line.)


        Give a man a fish:  <%-{-{-{-<

Re: Seperating values with spaces in array
by Corion (Patriarch) on Jan 17, 2016 at 11:46 UTC

    Where are you stripping leading zeroes? Or where are you adding the leading zeroes?

    Also, where is JSON coming into this problem?

    Is your input data maybe CSV? Maybe you want to use Text::CSV_XS?

      the JSON is for later dont worry about that. The txt file has a list of numbers "001, 002, 003.... Those leading zeros are fine as a string but are removed when turned into numeric data in the array.

        Perl does not magically turn strings into numeric data when putting them into an array. Maybe your problem happens when you output the data?

        Please show us some problematic input data and the output you get when you run your program as you have posted it.