I had got a script in Perl and my task is to do some changes in it. This of course means to understand which part does exactly what. I am not familiar with Perl language but I tried to read through some tutorials, but still some things are confusing me. And I got stuck in following part:
while (<KOEFICIENTYfile>) {
#_=(split(/\s+/, $_));
push(#ZAID,shift(#_));
$KOEFICIENTY{$ZAID[-1]}=[#_];
}
As I understands this part then it:
Reads line from filehandle KOEFICIENTYfile
Separates them by spaces (one or more)
Loads first item from this separated array into array ZAID (and in the process, removes it from #_)
??? Adds a rest of a separated array into array KOEFICIENTY? I am confused by curly brackets part and by square brackets after equals sign.
I think that I understood the meaning of #, $, #_ or negative indexing but this is beyond me. Can you please advice me on meaning of this?
[-1] indexing is just a shortcut way to say "last element of the array".
KOEFICIENTY is actually a hash (you can tell this because it is using curly braces, instead of square ones, around the index), so you're putting the rest of the array #_ into a hash called KOEFICIENTY with a key of the last element of the array.
If you include:
use Data::Dumper
at the top of the script and do
print Dumper(%KOEFICIENTY)
it will nicely format the output for you, which may help
The original coder was trying to be too clever using the negative offset. It would have been much more obvious if the code had been written with a simple temporary variable thus:
while (<KOEFICIENTYfile>) {
#_ = (split(/\s+/, $_));
my $key = shift(#_);
push(#ZAID, $key);
$KOEFICIENTY{$key} = [#_];
}
The braces on $KOEFICIENTY show that this is a "hash" of key/value pairs named %KOEFICIENTY, and not a normal array.
If you don't actually need to preserve the sort order of the keys you could just use keys %KOEFICIENTY to retrieve them instead of storing them in #ZAID.
#zaid is a list, into which the first part of the split is added.
%KOEFICIENTY is a hash, in which a reference to the rest of the split is stored as a list reference under the key of the first part.
So if the line is a b c, #zaid will get a and %KOEFICIENTY{'a'} will hold a reference to a list containing b and c.
Related
First question on stackoverflow :)
I'm going through the Ruby course on Codecademy and I'm stuck on something.
fruits = ["orange", "apple", "banana", "pear", "grapes"]
fruits.sort! {|first, second| second <=> first}
print fruits
I don't know how to phrase this question. On Codecademy the assignment was to set up the array to be displayed in reverse on the console. After some research, I was able to figure it out. I understand how it works and the order to put it in the code not why. I'm aware that "<=>" compares two objects, but how do the items within the array become objects when we don't declare them as such?
Secondly, what is the purpose of writing this code in this way when we could do fruits.sort.reverse?
First question: At various points in its operation the sort method has to compare pairs of objects to see what their relative ordering should be. It does the comparison by applying the block you pass to sort, i.e., {|first, second| second <=> first}. Not sure what you mean by "how do the items within the array become objects when we don't declare them as such?". All data in ruby is an object, so there's no declaration or conversion needed given that all variables are object references.
Second question: Yes, you could do fruits.sort.reverse, but that would require additional work after the sort to do the reverse operation. Also, reverse can't handle more complex sorting tasks, such as sorting people by multiple criteria such as gender & last name, or hair color, height, and weight. Writing your own comparator can handle quite complex orderings.
String literals can be used to create string objects in Ruby, there is no need to use the String class to create the object. The following two are equivalent:
"Hello, world!"
String.new("Hello, world!")
More information can be found here.
Secondly, what is the purpose of writing this code in this way when we could do fruits.sort.reverse?
Please contact Codecademy about this, but I suspect it's for learning more about how <=> works.
I need to iterate and parse 108 lines from a file and then sort them into 3 different hashes. (In one iterator.) (In Ruby)
I have the file loaded into the program and into the array I need to parse. When I try to make the iterator anyway I try to use the Regex Match command I get an error abut the unknown method. Is as simple that I can't use that method on a array?
lines = File.readlines('access_log')
lines.each.match(/^([:\d\.]+) .*\[.*\].*\"[A-Z]+ *(.+) HTTP/)
This and every other way I have tried to use the match method it hasn't worked.
This also doesn't anything for the hash, as I haven't done that yet.
/^([:\d\.]+) .*\[.*\].*\"[A-Z]+ *(.+) HTTP/.match(lines)
Have also tried this, but the error output appears that you cant run it on only the array. I beilive this is where I would need to tie the iterator in, but I'm stumped.
So, what's happening is that what readlines does is it slurps the entire text file.
So you have an array with the content of the textfile separated by a newline(and the newline is kept in every string in the array).
After that, you're doing lines.each, which brings out an enumerator. Then you're calling .match on the enumerator instead of the string itself
The proper way to do this would be
lines.each { |line| line.match(/^([:\d\.]+) .*\[.*\].*\"[A-Z]+ *(.+) HTTP/) }
However, the above actually won't do anything because all you're doing is iterating against each element and checking if it matches the REGEX.If you want it to actually do something, try...
matches = lines.map { |line| line.match(/^([:\d\.]+) .*\[.*\].*\"[A-Z]+ *(.+) HTTP/) }
Remember that the match method only works on strings. If match matches something, it returns an object of the class MatchData, else if it doesn't match anything-- nil.
My Lua script fails with the error
'}' expected near 'OF'
at the line where I declare a large array.
I used to have it split across multiple line like so:
local array = {lots,
of,
array,
elements}
but even after I put it in one line like so:
local array = {lots, of, array, elements}
I'm still getting the same error.
I'm pretty new to Lua so may be doing something completely stupid, but I've pored through my array several times looking for a misplaced character or extra { and I can't find one. Any help will be greatly appreciated
There's no problems with this snippet, see confirmation: http://ideone.com/d7v49D
local array = {lots,
of,
array,
elements}
Here we have new array construction, consisting of 4 global variable's values. Nothing special, no reserved keywords, etc.
I am currently having trouble filling up an array of customClass.
I try to fill it with a jsonFile. During my json parsing (using swiftyJSON) i loop and fill my array.
The problem is, at the end of my loop, it is still empty. I tested it in different ways, and here is my code:
That's the file where the problem is. In my loop I fill an Annotation, that I add with append to my array. The problem is what my print return. Here is a part of it:
It's just a small part of a huge jsonfile. And, my tmpAnnot.name is correctly printed every iteration. But when it comes to my Array, nothing.
So I'm completly lost and hope you could help me ^^
(And for the information, here is my custom class) :
And btw, I tried to print my array.count, and it's nil too
Im so sorry if the question has been posted. I couldn't find it in the entire website.
Change your JSONAnnotationList declaration to be an non-optional and assign it an empty array
var JSONAnnotationList: [UGOAnnotation] = []
You see, you have never created an array so there was nothing to be printed.
The whole point of optionals is to use them sparingly, not everywhere.
hash_test.pl
#a=("f","a","b");
$K{"f"}{"aa"}=1;
$K{"a"}{"aa"}=1;
$k{"b"}{"bb"}=1;
foreach(#a){
#c= sort keys %{$k{$_}};
}
print "#c\n";
foreach(#c) {...}
perl hash_test.pl
bb
I want to keep the keys of the hash into an array, so that I can use the array as an input for the following statements.
But it seemed that the assay #c just only hold the last element.
Could anyone tell me why or help me to improve the script?
You assign the array every time in the foreach, thus overwriting it every time. So you end up with only having the last thing assigned to it. If you move the print inside the foreach you'll see that they are all there.
To store those keys you need to add them to the array, not assign the array. I've corrected the typo $k to $K, and changed aa that goes with f to ff (expecting it to be a typo as well).
my #c;
foreach my $el (#a) {
push #c, sort keys %{$K{$el}};
}
print "#c\n";
This prints the line: ff aa bb. Every time through the loop all keys found in the hash for a particular array element are added to #c, each as a separate element. So #c will contain all bottom-level keys across the whole data structure.
However, there is more that I would like to suggest.
Always use strict; and use warnings; This is not pedantry but it directly helps. I never write code without them. The typo would be caught here, for example.
Use descriptive variable names. Specifically, single-letter variable names are just too easy to confuse, unless in very short loops or where it is crystal clear what they are. (For example, a typo like this couldn't really happen.) Most importantly, the code is going to be far nicer to work with. That generally results in better code.
Please use good indentation and spacing. It helps a lot, in many ways.
A useful core package for nested data structures is Data::Dumper, which can print the whole thing nicely formatted so we can see it. Try to add to the end of your code
use Data::Dumper;
print Dumper(\%K);
There are yet others that do the same or similar.
Here is another way to do what you ask.
my #lowest_keys = map { sort keys %{$K{$_}} } #a;
I call them lowest_keys to emphasize that these are the ones from the last hash in your data structure, the bottom of it. The map applies processing in the block { ... } to each element of #a in turn, returning a list with all these results. (If any one result itself is a list, with more elements than one, it gets merged into the overall output list. So this may create the output list with many more elements than the input.) This list can then be assigned to an array, as above, or passed on to another function that expects a list as input, or interated over.
The map is generally used to transform an array into another, by doing to each element what is in { ... } block. Its close cousin grep is used to filter, so passing through only the elements of the input list for which the condition in { ... } evaluates to true, forming the output list. For example, filter out undefined array elements: my #good = grep { defined } #all
Variable names are case sensitive, so %K... and %k... are not the same.
Always use
use strict;
use warnings;
and declare your variables with my. That prevents you from making this kind of mistakes.