str_replace syntax in perl script - sql

In my below script, the str_replace(rtrim(c_manager),'''','_') doesn't seem to work.
I want to replace single quotes with underscores for my arguments. For example:
Input: `S'achin`
Result: `S_achin`
$sql = 'select rtrim(f_admin_disabled),'."\n".
' convert(varchar,t_password,101),'."\n".
' rtrim(c_email),'."\n".
' str_replace(rtrim(c_manager),'''','_'),'."\n".
' rtrim(c_mgr_email)'."\n".
' from tuserprofile'."\n".
' where ic_user1 = '."'$user_id'"."\n";

If you want to have single quotes in a single quoted string to produce str_replace(rtrim(c_manager),'''','_'), you need to either escape them:
' str_replace(rtrim(c_manager),\'\'\'\',\'_\'),'
or use a different delimiter:
q! str_replace(rtrim(c_manager),'''','_'),!

to replace a character in string
$string=~s/'/_/g;
Syntax
$string=~s/<string>/<replace_string>/g;

Use this subroutine.
sub str_replace {
my ($s) = #_;
$s =~ s/'/_/g;
return $s;
}

Related

LIKE operator with a bindvar pattern which works also for special characters

I have such a query:
WHERE x LIKE $1
, where $1 is a bindvar string built in the backend:
$1 = "%" + PATTERN + "%"
Is it possible to build a LIKE PATTERN in that way that special characters (% and _) are escaped, so I have the same functionality, but it works for all possible PATTERN values.
You would want to escape the literal % and _ with backslash. For example, in PHP we might try:
$pattern = "something _10%_ else";
$pattern = preg_replace("/([%_])/", "\\\\$1", $pattern);
echo $pattern; // something \_10\%\_ else

POWERSHELL: making a literal string out of a expanded string

I have a string that I build from a couple sources to do matching with later, the short of my code so far is:
$temp = "some\good"
if("some text" -match $temp)
My representation of $temp is simple but actually it is built, this is an example of how it can get built, so no, in this case changing " for ' to pass a literal to $temp won't work. If I hard code the if to use a literal string version of $temp, it works so its a matter of converting the value in $temp to a literal string.
I get the following error when I run my code:
parsing "some\good" - Unrecognized escape sequence \g.
At [not important]
+ if($temp2 -match $temp)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], ArgumentException
+ FullyQualifiedErrorId : System.ArgumentException
"Converting to literal string" won't help you here. String is a string, it only matters how it's being used, i.e. if the content is being interpreted in some way.
-match operates on regex, and that's it, you can't change that, you'd have to escape every all characters that have a meaning in regex.
But you can use select-string instead, which has a switch for simple matching:
$text = "some text"
$patt = "some\good"
if (($text | Select-String -SimpleMatch -Pattern $patt | Measure-Object).count -gt 0) {
Write-Host "match"
} else {
Write-Host "nomatch"
}

Perl replace with variable

I'm trying to replace a word in a string. The word is stored in a variable so naturally I do this:
$sentence = "hi this is me";
$foo=~ m/is (.*)/;
$foo = $1;
$sentence =~ s/$foo/you/;
print $newsentence;
But this doesn't work.
Any idea on how to solve this? Why this happens?
Perl lets you interpolate a string into a regular expression, as many of the answers have already shown. After that string interpolation, the result has to be a valid regex.
In your original try, you used the match operator, m//, that immediately tries to perform a match. You could have used the regular expression quoting operator in it's place:
$foo = qr/me/;
You can either bind to that directory or interpolate it:
$string =~ $foo;
$string =~ s/$foo/replacement/;
You can read more about qr// in Regexp Quote-Like Operators in perlop.
You have to replace the same variable, otherwise $newsentence is not set and Perl doesn't know what to replace:
$sentence = "hi this is me";
$foo = "me";
$sentence =~ s/$foo/you/;
print $sentence;
If you want to keep $sentence with its previous value, you can copy $sentence into $newsentence and perform the substitution, that will be saved into $newsentence:
$sentence = "hi this is me";
$foo = "me";
$newsentence = $sentence;
$newsentence =~ s/$foo/you/;
print $newsentence;
You first need to copy $sentence to $newsentence.
$sentence = "hi this is me";
$foo = "me";
$newsentence = $sentence;
$newsentence =~ s/$foo/you/;
print $newsentence;
Even for small scripts, please 'use strict' and 'use warnings'. Your code snippet uses $foo and $newsentence without initialising them, and 'strict' would have caught this. Remember that '=~' is for matching and substitution, not assignment. Also be aware that regexes in Perl aren't word-bounded by default, so the example expression you've got will set $1 to 'is me', the 'is' having matched the tail of 'this'.
Assuming you're trying to turn the string from 'hi this is me' to 'hi this is you', you'll need something like this:
my $sentence = "hi this is me";
$sentence =~ s/\bme$/\byou$/;
print $sentence, "\n";
In the regex, '\b' is a word boundary, and '$' is end-of-line. Just doing 's/me/you/' will also work in your example, but would probably have unintended effects if you had a string like 'this is merry old me', which would become 'this is yourry old me'.

dbext seems to think ( is a sql statement terminator

I have this in the .sql file in my buffer:
CREATE TABLE WH.dbo.customer(
id INTEGER NOT NULL,
cust_name VARCHAR(30) NOT NULL,
phone_nbr VARCHAR(30) NULL,
PRIMARY KEY(id)
);
If I am in normal mode and the cursor is on TABLE then I sould be able to hit either <Leader>se or command gVim to :DBExecSQLUnderCursor and the statement should be executed as dbext should find CREATE and ; and then execute the script in between. But i get the following message:
Last SQL:
CREATE TABLE WHAnalysis.dbo.customer(
If I highlight all the script and choose Execute SQL (Visual selection) from the plugin menu then it runs fine.
What is going on? Could it be a setting in my _vimrc?:
set nocompatible
source $VIMRUNTIME/vimrc_example.vim
source $VIMRUNTIME/mswin.vim
behave mswin
set diffexpr=MyDiff()
" Use CTRL-S for saving, also in Insert mode
:nnoremap <C-S> :<C-U>update<CR>
:vnoremap <C-S> :<C-U>update<CR>gv
:cnoremap <C-S> <C-C>:update<CR>
:inoremap <C-S> <C-O>:update<CR>
" Microsoft SQL Server
let g:dbext_default_profile_WH = 'type=SQLSRV:user=dbuser:passwd=dbuserpassword:dsnname=SQLOLEDB.1:srvname=dwdb'
set nocp
call pathogen#infect()
syntax on
filetype plugin indent on
"Mouse and backspace
set mouse=a
function MyDiff()
let opt = '-a --binary '
if &diffopt =~ 'icase' | let opt = opt . '-i ' | endif
if &diffopt =~ 'iwhite' | let opt = opt . '-b ' | endif
let arg1 = v:fname_in
if arg1 =~ ' ' | let arg1 = '"' . arg1 . '"' | endif
let arg2 = v:fname_new
if arg2 =~ ' ' | let arg2 = '"' . arg2 . '"' | endif
let arg3 = v:fname_out
if arg3 =~ ' ' | let arg3 = '"' . arg3 . '"' | endif
let eq = ''
if $VIMRUNTIME =~ ' '
if &sh =~ '\<cmd'
let cmd = '""' . $VIMRUNTIME . '\diff"'
let eq = '"'
else
let cmd = substitute($VIMRUNTIME, ' ', '" ', '') . '\diff"'
endif
else
let cmd = $VIMRUNTIME . '\diff'
endif
silent execute '!' . cmd . ' ' . opt . arg1 . ' ' . arg2 . ' > ' . arg3 . eq
endfunction
nnoremap <Leader>p :pyf P:\Computer Applications\Python\
"quick quit command
noremap <Leader>e :quit<CR> "quits the current window
" Rebind <Leader> key
let mapleader = ","
map <Leader>n <esc>:tabprevious<CR>
map <Leader>m <esc>:tabnext<CR
I spoke to the plugin maintainer David Fishburn - I was amazed at the time-out he took to help a novice like me: great guy.
Initially he suggested
I believe the cmd terminator for SQLSRV is "\ngo\n" not ";".
If you want to change it temporarily to try in this buffer run:
:DBSetOption cmd_terminator=';'
Try the cmd again.
If that works you can either override the default or change your
profile to override it.
Then in answer to some further related questions:
Q1. What is "\ngo\n" ?
Because the string is enclosed in double quotes, Vim treats escaped
characters differently. \n - newline go \n - newline
So for SQL Server this would be typical:
CREATE PROCEDURE
BEGIN
END
go
Which is actually:
"END\ngo\n"
In other words, "go" has to be on a newline, with only "go" on the
line.
Q2. Do I just add the following to _vimrc for it to become permanent?:
DBSetOption cmd_terminator=';'
No. :DBSetOption is used to modify current buffer settings only, not
permanent settings.
The best thing you can do is read through :h dbext.txt.
The specific answer to your question lies in :h dbext-configure-options
5.3 Database Specific Options dbext-configure-options
The command terminator is automatically added to a command before it is
sent to the database. The command options are also added to the command
line used to execute the statement. >
dbext_default_SQLSRV_bin = "osql"
dbext_default_SQLSRV_cmd_header = ""
dbext_default_SQLSRV_cmd_terminator = "\ngo\n"
dbext_default_SQLSRV_cmd_options = '-w 10000 -r -b -n'
dbext_default_SQLSRV_extra = ''
So, to permanently override for all buffers in your .vimrc you would
add:
let g:dbext_default_SQLSRV_cmd_terminator = ";"

Variable expansion and escaped characters

In PowerShell, you can expand variables within strings as shown below:
$myvar = "hello"
$myvar1 = "$myvar`world" #without the `, powershell would look for a variable called $myvarworld
Write-Host $myvar1 #prints helloworld
The problem I am having is with escaped characters like nr etc, as shown below:
$myvar3 = "$myvar`albert"
Write-Host $myvar3 #prints hellolbert as `a is an alert
also the following doesnt work:
$myvar2 = "$myvar`frank" #doesnt work
Write-Host $myvar2 #prints hellorank.
Question:
How do I combine the strings without worrying about escaped characters when I am using the automatic variable expansion featurie?
Or do I have to do it only this way:
$myvar = "hello"
$myvar1 = "$myvar"+"world" #using +
Write-Host $myvar1
$myvar2 = "$myvar"+"frank" #using +
This way is not yet mentioned:
"$($myvar)frank"
And this:
"${myvar}frank"
This seems kind of kludgy, but as another option, you can add a space and a backspace:
$myvar = "hello"
$myvar1 = "$myvar `bworld"
$myvar1
Yet another option is to wrap your variable expression in a $():
$myvar3 = "$($myvar)albert"
Write-Host $myvar3
One other option is through the format operator:
"{0}world" -f $myvar
Another option is a double-quoted here-string:
$myvar = "Hello"
$myvar2 = #"
$myvar$("frank")
"#