Perl map to map [duplicate] - perl

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How do I create a hash of hashes in Perl?
I need to create something which is an equivalent of map : name(string) to map date(string/int) to value, i.e. a map { string => map { string => value } } .
How should i go about it in perl ?
The following code does not work.
my %strtomap_;
# given $str_, $date_, $val_
if ( ! exists $strtomap_ { $str_ } )
{
my %new_map_date_to_val_ ;
$new_map_date_to_val_{$date_} = $val_;
$strtomap_ { $str_ } = %new_map_date_to_val_ ;
}
else
{
$strtomap_ { $str_ } { $date_ } = $val_;
}

Values of aggregate types (hashes and arrays) can only be scalars, not other aggregate types. So if you are going to explicitly use something like your %new_map_date_to_val_, you need to store a reference to it instead:
my %new_map_date_to_val;
$new_map_date_to_val_ { $date_ } = $val_;
$strtomap_ { $str_ } = \%new_map_date_to_val_;
though you can use an anonymous hash instead:
$strtomap_ { $str_ } = { $date_ => $val _ };
And in fact, the whole exists test is not needed, since simply dereferencing an undefined value in this kind of way will autovivify a hash reference for you. Your whole code can just be:
my %strtomap_;
$strtomap_ { $str_ } { $date_ } = $val_;

Related

I want to pass some text into the textfield but something wrong....idk why print() is work [duplicate]

This question already has an answer here:
how can i put these print text into Textfield?
(1 answer)
Closed 5 years ago.
swift4 Xocode9
UNUserNotificationCenter.current().getPendingNotificationRequests {
DispatchQueue.main.async {
// Contextual closure type '() -> Void' expects 0 arguments,
// but 1 was used in closure body
let str:String = ""
self.finalresulter.text = str
self.finalresulter.text = "\($0.map{$0.content.title})"
}
print($0.map { $0.content.title},",",$0.map { $0.content.subtitle},","
,$0.map { $0.content.body},","
,$0.map { $0.trigger!})
}
please help...how to fix..
Try this:
notificatecontent.text = "\($0.map{$0.content.title})"
The issue appears to be identical to your other question. In order not to replicate existing answer I gave there, I would only mention the second part, which would look like:
UNUserNotificationCenter.current().getPendingNotificationRequests { requests in
// Textfield assignment here ...
print(requests.map { $0.content.title},",",requests.map { $0.content.subtitle},","
,requests.map { $0.content.body},","
,requests.map { $0.trigger!})
}
But, unless you explicitly want to print everything on one line, this print should be better replaced with regular for loop (or at least a forEach method):
// 1
for item in requests {
print(item.content.title, item.content.subtitle, item.content.body)
}
// 2
requests.forEach {
print($0.content.title, $0.content.subtitle, $0.content.body)
}

How to get index of macro repetition single element

I need to get index of macro repetition element to write next code:
struct A {
data: [i32; 3]
}
macro_rules! tst {
( $( $n:ident ),* ) => {
impl A {
$(
fn $n(self) -> i32 {
self.data[?] // here I need the index
}
),*
}
}
}
I know one way to do it: just tell user to write index by hands:
( $( $i:ident => $n:ident ),* )
But is there a more elegant way which does not require user's action?
The easiest way is to use recursion, like so:
struct A {
data: [i32; 3]
}
macro_rules! tst {
(#step $_idx:expr,) => {};
(#step $idx:expr, $head:ident, $($tail:ident,)*) => {
impl A {
fn $head(&self) -> i32 {
self.data[$idx]
}
}
tst!(#step $idx + 1usize, $($tail,)*);
};
($($n:ident),*) => {
tst!(#step 0usize, $($n,)*);
}
}
tst!(one, two, three);
fn main() {
let a = A { data: [10, 20, 30] };
println!("{:?}", (a.one(), a.two(), a.three()));
}
Note that I changed the method to take &self instead of self, since it made writing the example in the main function easier. :)
Each step in the recursion just adds 1 to the index. It is a good idea to use "typed" integer literals to avoid compilation slowdown due to lots and lots of integer inference.

CoffeeScript: Create a shallow copy of an object and rename/drop properties with a one-liner

Given:
externalObject = {
UglyKeyOne: 'val1'
UglyKeyTwo: 'val2'
UglyUnusedKey: 'boo'
}
Is there a way to do the below 2 lines, in a one liner? i.e. to create newObject, and use the destructuring assignment in one step?
{ UglyKeyOne: keyOne, UglyKeyTwo: keyTwo } = externalObject
newObject = { keyOne, keyTwo }
This works:
newObject = { keyOne, keyTwo } = { keyOne: externalObject.UglyKeyOne, keyTwo: externalObject.UglyKeyTwo }

How can I find the index of an item in Swift? [duplicate]

This question already has answers here:
How to find index of list item in Swift?
(23 answers)
Closed 7 years ago.
Is there a method called indexof or something similar?
var array = ["Jason", "Charles", "David"]
indexOf(array, "Jason") // Should return 0
EDIT: As of Swift 3.0, you should use the .index(where:) method instead and follow the change in the Swift 2.0 edit below.
EDIT: As of Swift 2.0, you should use the indexOf method instead. It too returns nil or the first index of its argument.
if let i = array.indexOf("Jason") {
print("Jason is at index \(i)")
} else {
print("Jason isn't in the array")
}
Use the find function. It returns either nil (if the value isn't found) or the first index of the value in the array.
if let i = find(array, "Jason") {
println("Jason is at index \(i)")
} else {
println("Jason isn't in the array")
}
In Swift 2.0 (Xcode 7.1b), you can use
if let result = array.indexOf("Jason")
while find(array, "Jason") is deprecated.
I made this function like above, but it return array of indexes
extension Array {
func indexesOf<T : Equatable>(object:T) -> [Int] {
var result: [Int] = []
for (index,obj) in enumerate(self) {
if obj as T == object {
result.append(index)
}
}
return result
}
}
Maybe it will be useful for you
Array can be bridged to an NSArray, so you can use:
array.bridgeToObjectiveC().indexOfObject("Jason")
An extension of Array can work wonders here. Here's an implementation shared in this StackOverflow answer:
extension Array {
func find (includedElement: T -> Bool) -> Int? {
for (idx, element) in enumerate(self) {
if includedElement(element) {
return idx
}
}
return nil
}
}
You can add an Array Extension that does exactly what you want, i.e:
extension Array {
func indexOf<T : Equatable>(x:T) -> Int? {
for i in 0..self.count {
if self[i] as T == x {
return i
}
}
return nil
}
}
Which now lets you use .indexOf() on all Swift arrays, e.g:
["Jason", "Charles", "David"].indexOf("Jason") //0
While the response from Max is great, it does not let you find multiple indexes of multiple objects, ie. indexes of the subset of the array. If you need that functionality, extensions are, as always, your best friend
func indexesOfSubset<T : Equatable>(objects : [T]) -> [Int] {
// Create storage for filtered objectsand results
var unusedObjects = objects
var result : [Int] = []
// Enumerate through all objects in array
for (index, obj) in enumerate(self) {
// Enumerate again through all objects that has not been found
for x in unusedObjects {
// If we hit match, append result, remove it from usused objects
if obj as! T == x {
result.append(index)
unusedObjects = unusedObjects.filter( { $0 != x } )
break
}
}
}
// Get results
return result
}
Note* : Works on Swift 1.2, if you want compatibility with 1.1, replace as! -> as

How to compare self.title to a string in Objective C?

What am I doing wrong in the below code? My if statement is missing something:
if ([self.title] = "Upcoming Events") {
} else {
}
Correct would be:
if( [self.title isEqualToString:#"Upcoming Events"] )
self.title is a pointer, you can only compare it to other pointers using == not their values.
if ([self.title isEqualToString:#"Upcoming Events"]) {
NSLog(#"True");
} else {
NSLog(#"False");
}
You just have to write like this:
if([self.title isEqualToString:#"Upcoming Events"])
{
}
else
{
}
also .... in a if you should use "==" instead of "=". When there is "==" it is checking if they are equal while if there is "=" it gives the first one the value of the second.