0

I have this array of files which looks like this :

my @html_pages_files = ("html.17", "html.9", "html.0", "html.10");

I will put the extension of the file after the sort part. Basically the file name will be /html.\d/. The thing is I'm trying to sort it using map and sort function :

map { $_->[1] }
  sort { $a->[0] <=> $b->[0] }
     map { /html\.(.*)/; [$1, $_] }
        @html_pages_files;
print "@html_pages_files\n";

However the output remains the same as the original array. I've followed step by step @Chas. Owens answer here : Using Perl, how can I sort an array using the value of a number inside each array element?. Note that I'm pretty new to perl so I don't get all the details.

Does anybody seed where the error is ? Thank you!!!

1
  • 1
    For one, you're not checking to see if the regex match inside that map block succeeds. Right now if it doesn't match for some reason, you'll never know it and $1 will have the value from the previous regex match. I'd change it to /.../ or die if you expect that it will always pass. Commented Mar 7, 2013 at 16:58

2 Answers 2

6

You never save the sorted results!

@html_pages_files =
   map { $_->[0] }
    sort { $a->[1] <=> $b->[1] }
     map { /html\.(.*)/; [$_, $1] }
      @html_pages_files;

(For consistency, I always put the whole string in the first element of the array.)

Sign up to request clarification or add additional context in comments.

Comments

4

Your sorting logic looks correct but you are not assigning the result of the operation to anything, so you are not changing @html_pages_files. Try

@html_pages_files = map {$_->[1] } 
                    sort {$a->[0] <=> $b->[0]} 
                    map {/html\.(.*)/; [$1, $_]} @html_pages_files;

2 Comments

I've got it. actually you have to create a knew array in order to work, it looks like this : my @sorted = map{$_->[1]} sort{$a->[0] <=> $b->[0]} map{/html\.(.*)/; [$1, $_]} @html_pages_files; Nevertheless thank you for your advices!!!
@user2007958, You can, but you don't have, as both of us have shown.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.