Skip to content
Advertisement

Having some issues with Perl Splitting and Merging Functions

First and foremost, I’m not familiar with Perl at all. I’ve been studying C++ primarily for the last 1/2 year. I’m in a class now that that is teaching Linux commands, and we have short little topics on languages used in Linux, including Perl, which is totally throwing me for a loop (no pun intended). I have a text file that contains a bunch of random numbers separated by spaces and tabs, maybe even newlines, that gets read into the program via a filehandle. I’m supposed to write 2 lines of code that split the lines of numbers and merge them into one array, inside of a foreach loop. I’m not looking for an answer, just a nudge in the right direction. I’ve been trying different things for multiple hours and feel totally silly I can’t get it, I’m totally lost with the syntax. Its just a bit odd not working inside a compiler and out of my comfort zone working outside of C++. I really appreciate it. I’ve included a few photos. Basically, the code we are writing it just to store the numbers and the rest of the program will determine the smallest number and sum of all numbers. Mine is currently incorrect because I’m not sure what to do. In the output photo, it will display all the numbers being entered in via the text file, so you can see them.

code

output

Advertisement

Answer

Several things to fix here. First of all, please don’t post screenshots of your sample data or code, as it makes it impossible to copy and paste to test your code or data. Post your code/data by indenting it with four spaces and a newline preceding the code block.

Add use strict; in your script. This should be lesson 0 in your class. After that add my to all variable declarations.

To populate @all_numbers with contents of each line’s numbers, without using push, you can use something like this:

foreach my $line (@output_lines)
{
    my @numbers = split /s/, $line;
    @all_numbers = (@all_numbers, @numbers);
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement