C# equivalent of perl's $_ - c#

Is there an equivalent to Perl's $_ function? I'm rewriting some old perl scripts in C# and I never learned any perl. Heres an example of what i'm trying to figure out
sub copyText {
while($_[0]){
$_[1]->Empty();
$_[0] = $_[1]->IsText();
sleep(1);
}

First of all, $_ is not a function. It's just an ordinary variable (that happens to be read and changed by a lot of builtins).
Second of all, the code you posted does not use $_. It's accessing elements of #_, the parameter list.
A more more readable version of the code you posted would be:
sub copyText {
my ($arg1, $arg2) = #_;
while ($arg1) {
$arg2->Empty();
$arg1 = $arg2->IsText();
sleep(1);
}
$_[0] = $arg1; # arg1 is passed by reference
}
arg1 is a boolean passed by reference.
arg2 is some kind of object with a method named Empty and one named IsText.
Sorry, I don't know C#, but hopefully you can move on with this.

Perl's $_ function
It's not a function. It's a pronoun meaning 'it'.
There's another special variable #_, which is a pronoun meaning 'them'.
There's no analogue in C#.

Related

Matching and replacing function expressions

I need to do some very light parsing of C# (actually transpiled Razor code) to replace a list of function calls with textual replacements.
If given a set containing {"Foo.myFunc" : "\"def\"" } it should replace this code:
var res = "abc" + Foo.myFunc(foo, Bar.otherFunc( Baz.funk()));
with this:
var res = "abc" + "def"
I don't care about the nested expressions.
This seems fairly trivial and I think I should be able to avoid building an entire C# parser using something like this for every member of the mapping set:
find expression start (e.g. Foo.myFunc)
Push()/Pop() parentheses on a Stack until Count == 0.
Mark this as expression stop
replace everything from expression start until expression stop
But maybe I don't need to ... Is there a (possibly built-in) .NET library that can do this for me? Counting is not possible in the family of languages that RE is in, but maybe the extended regex syntax in C# can handle this somehow using back references?
edit:
As the comments to this answer demonstrates simply counting brackets will not be sufficient generally, as something like trollMe("(") will throw off those algorithms. Only true parsing would then suffice, I guess (?).
The trick for a normal string will be:
(?>"(\\"|[^"])*")
A verbatim string:
(?>#"(""|[^"])*")
Maybe this can help, but I'm not sure that this will work in all cases:
<func>(?=\()((?>/\*.*?\*/)|(?>#"(""|[^"])*")|(?>"(\\"|[^"])*")|\r?\n|[^()"]|(?<open>\()|(?<-open>\)))+?(?(open)(?!))
Replace <func> with your function name.
Useless to say that trollMe("\"(", "((", #"abc""de((f") works as expected.
DEMO

What is equivalent to VB.NET's Length keyword in C#?

I wrote VB.NET code like this:
d = Data.IndexOf("</a>", ("target='_top' class='ab1'>").Length() + s).
I want to write this in C#. When I wrote the above code in C#, it said there was an error with the Length keyword. How do I write the above code in C#?
Length is not a keyword in C# - it is either a property or an extension method on the object (like a string) that you are trying to manipulate.
So if it is a string you are using this will work:
myString.Length
(notice how the brackets are missing because it is a property).
You have an extra set of parentheses:
d = Data.IndexOf("</a>", "target='_top' class='ab1'>".Length + s)
Try that
Check this link out:
In it, you can easliy switch between C# to a VB good, to help you migrate:
http://msdn.microsoft.com/en-us/library/system.string.length.aspx#Y242

In this IronPython example what is the # symbol doing and how is it implemented?

http://www.ironpython.info/index.php/Using_Python_Classes_from_.NET/CSharp_IP_2.6
string code = #"
print 'test = ' + test
class MyClass:
def __init__(self):
pass
def somemethod(self):
print 'in some method'
def isodd(self, n):
return 1 == n % 2
";
Is that '#' part of C# or is that something added by IronPython? If the latter, how do you do that in C#, some kind of operator overloading (basically could I then make '#' do whatever I want, etc)? Example implementation would be great. Otherwise, what's going on here?
#"" is a verbatim string literal in C#. That is, escape characters inside it are not interpreted.
In this case, the python code is being stored in the C# code string variable, and then is compiled into a CompiledCode from a ScriptSource using a ScriptEngine (which is itself created using Python.CreateEngine()).
The # is part of the C# code. It means that the string is a verbatim string literal. The string holds the Python code to be executed.
string path = #"C:\Sweet\now\I\can\use\backslashes\without\writing\them\all\twice.txt"

how to get a String with String.Format to execute?

I have a little chunk of code (see below) that is returning the string:
string.Format("{0}----{1}",3,"test 2");
so how do I get this to actually "Execute"? To run and do the format/replacement of {0} and {1}?
My Code snippet:
StringBuilder sb = new StringBuilder();
sb.Append("{0}----{1}\",");
sb.AppendFormat(ReturnParamValue(siDTO, "siDTO.SuggestionItemID,siDTO.Title"));
string sbStr = "=string.Format(\""+sb.ToString()+");";
yes, ReturnParamValue gives the actually value of the DTO.
Anyways, I've taken a look at the following (but it doesn't say how to execute it:
How to get String.Format not to parse {0}
Maybe, I just should put my code snippet in a method. But, what then?
Why are you including String.Format in the string itself?
If you're looking for a generic "let me evaluate this arbitrary expression I've built up in a string" then there isn't a simple answer.
If, instead, you're looking at how to provide the parameters to the string from a function call, then you've got yourself all twisted up and working too hard.
Try something like this, based on your original code:
string result
= string.Format(
"{0}----{1}",
ReturnParamValue(siDTO, "siDTO.SuggestionItemID,siDTO.Title"));
Though, this won't entirely work since your original code seems to be only providing a single value, and you have two values in your format string - the {0} will be replaced with the value from your function, and {1} left unchanged.
What output are you expecting?
Does your ReturnParamValue() function try to return both the label and the value in a single string? If it does, and if they're comma separated, then you could try this:
var value = ReturnParamValue(siDTO, "siDTO.SuggestionItemID,siDTO.Title"));
var pieces = string.Split(',');
string result
= string.Format( "{0}----{1}", pieces[0], pieces[1]);
Though this is seriously working too hard if ReturnParamValue() is a method you control.
Update Fri 6 August
Check out the declaration for string.Format() as shown on MSDN:
public static string Format(
string format,
params Object[] args
)
Unlike the special casing you might have seen in C for printf(), there's nothing special or unusual about the way string.Format() handles multiple parameters. The key is the params keyword, which asks the compiler to provide a little "syntactic sugar" where it combines the parameters into an array for you.
Key here is that the wrapping doesn't happen if you're already passing a single object[] - so if you wanted to, you could do something like this:
object[] parameters
= ReturnParamValues(siDTO, "siDTO.SuggestionItemID,siDTO.Title");
string result
= string.Format("{0}----{1}----{2}", parameters);
Though, if I saw something like this in any codebase I maintained, I'd be treating it as a code-smell and looking for a better way to solve the problem.
Just because it's possible doesn't mean it's advisable. YMMV, of course.
I don't think you can execute it. Java is not really a interpreted language.
You may make use of scripting languages (which can even embed in your Java app as I know, start from JDK6) for such purpose, like Groovy
You could use RegEx to parse the three parameters out of the string, and then pass them to a real, actual string.Format method :-)
It looks like what you want is something like this:
string sbStr = string.Format("{0}----{1}", siDTO.SuggestionItemID, siDTO.Title);
Maybe i didn't understand your question completely, but it sounds like you need to format a format-string. If that's true you could maybe try something like this:
int width = 5;
string format = String.Format("{{0,{0}}}----{{1,{0}}}", width);
string result = String.Format(format, "ab", "cd");
So the trick is simply to escape the { or } by using a double {{ or }}.

In C# VS2008 how to replace (string)aaa to aaa.ToString()

I just converted a VB.net solution into C# solution. But lots of variables have been coverted like:
string var1 = (string)1;
string var2 = (string)intVar; //intVar is a int value
I just want to convert all (string)XXXX to XXXX.ToString() by using some Regular expressions or some other replace methods.
Can someome help me out?
find: \(string\){:a*}
replace: \1.ToString()
Back up your solution first!
The text editor Notepad++ has regular expression support. You may try something like: Replace [(]string[)][ ]*([^ .\t;/]*) with \1.ToString().
This turns this:
(string) xyz;
(string) abc.123;
(string)alf;
(string)argu ment
into this:
xyz.ToString();
abc.ToString().123;
alf.ToString();
argu.ToString() ment
This however, does not handle the case of (string) aFunction( obj1, obj2 ).
You may want to handle these by yourself first, or build another regexp.
I am not sure if you really want to do this as a mass conversion. As in all reality in your example, you should end up with the following.
string var1 = "1";
and
string var2 = intVar.ToString();
There is no need for your first example to be doing a cast, when it can be a string from the beginning.
Suggest you to use this one
Find: \(string\){(.*)}{:Po}
Replace: \1.ToString()\2
Good luck!
I am not too familiar with regex but I offer a warning instead. You might not want to replace all (string)xxx to xxx.toString() because (as you know I am sure) (string) is casting and a ToString() is a method call. You can only cast something as string if the object is a descendant of string. You can call ToString() if the implementor of the class overrode the ToString() method. If not then you are just going to get the default implementation.
Well, the reason that you get the extra code in the conversion, is that you don't have Option Strict On in the VB code. If you had, you wouldn't be able to do those implicit conversions in the first place.
So, the VB code should look like this, and the C# code would then look right in the conversion:
var1 As String = "1"
var2 As String = intVar.ToString
To fix this after the conversion is done is quite beyond what a regular expression is capable of. Sure, you could make an expression that would convert all (string)x to x.ToString(), but that would probably cause more problems that it fixed...

Categories

Resources